Skip to content

Instantly share code, notes, and snippets.

@andrewxhill
Last active Aug 29, 2015
Embed
What would you like to do?
County selector example
<!DOCTYPE html>
<html>
<head>
<title>County Selector</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<link rel="shortcut icon" href="http://cartodb.com/assets/favicon.ico" />
<style>
html, body, #map {
height: 100%;
padding: 0;
margin: 0;
}
</style>
<link rel="stylesheet" href="http://libs.cartocdn.com/cartodb.js/v3/themes/css/cartodb.css" />
</head>
<body>
<div id="map"></div>
<!-- include cartodb.js library -->
<script src="http://libs.cartocdn.com/cartodb.js/v3/cartodb.js"></script>
<script>
function main() {
// Initiate our Leaflet Map
var map = new L.Map('map', {
zoomControl: true,
center: [39.35129035526705, -97.97607421875],
zoom: 5
});
// Add a baselayer to the map
L.tileLayer('http://{s}.api.cartocdn.com/base-light-nolabels/{z}/{x}/{y}.png').addTo(map);
// Get the 'county' variable from our GET parameters
var c = getQueryVariable('county');
// Create our data layer using our CartoDB Visualization
cartodb.createLayer(map, 'http://andrew.cartodb.com/api/v2/viz/7fff1080-f64b-11e3-82d4-0e230854a1cb/viz.json',{
sql: "SELECT *, true as highlight FROM us_counties_4"
})
.addTo(map)
.on('done', function(layer) {
layer.getSubLayer(0).setSQL("SELECT *, name ilike '"+c+"' as highlight FROM us_counties_4 ORDER BY highlight ASC");
// After the layer has been added to the map, let's do stuff
// If county existed, do stuff
if(c){
// Query our CartoDB table to see if we find the County
// This could be improved if we also required a state
var sql = cartodb.SQL({ user: 'andrew' });
sql.execute("select st_x(st_centroid(the_geom)) lon, st_y(st_centroid(the_geom)) lat from us_counties_4 where name ilike '" + c + "'").done(function(data) {
// Check if there are results
if(data.rows.length > 0){
map.setView([data.rows[0].lat,data.rows[0].lon], 9, {animate: true})
}
})
console.log(c);
}
}).on('error', function() {
cartodb.log.log("some error occurred");
});
}
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', variable);
}
// you could use $(window).load(main);
window.onload = main;
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment