Skip to content

Instantly share code, notes, and snippets.

@mpmckenna8
Last active November 9, 2015 04:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mpmckenna8/2725ea439744db4a643e to your computer and use it in GitHub Desktop.
Save mpmckenna8/2725ea439744db4a643e to your computer and use it in GitHub Desktop.
CartoDB SQL API simple exameple

So getting the map layers from CartoDB is nice and easy as shown in the last bl.ock but at first I was having trouble understanding how to access all the data I generated the map with throught the layers part of the API, and that's because you can't. Well, you can indirectly by the user clicking on a object with a pop up, and for each click a API call is made and the appropriate information to fill in the popup of the given feature will load into the popup.

So what if I wanted to display a list of all the parks in the layer I had, I don't want to do a request mimicking clicks on each feature cause that would suck. CartoDB has an SQL API to make queries of data from your databases, and you can use all sorts of Postgis spatial query features to get at that data and have it returned to you in a nice json format so you can pop it into your webpage nice and quick and easy. Plus you get a cartoDB id which might make it easy to call events from the main layer. Because there are features in the source database (parks in this example) features which share the same unit_name attribute the sql query uses the distinct keyword so I can make a list of all the park names which fills along the left side of the page. Check out the code and let me know if there are any stupidities or if it helped you somehow.

I decided to make these simple bl.ocks because my first attempt at using the CartoDB api was with a little project which I started with Bootleaf so the CartoDB related stuff was dispersed over a few files and wa kind of a jenky implementation. Please check it out and give me some feedback or let me know if you're having trouble getting it to work. It should basically be a more complicated version of this map but with campsites too, and a nice search box.

<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/list.js/1.1.1/list.min.js"></script>
<link rel="stylesheet" href="http://libs.cartocdn.com/cartodb.js/v3/themes/css/cartodb.css" />
<script src="http://libs.cartocdn.com/cartodb.js/v3/cartodb.js"></script>
<!--[if lte IE 8]>
<link rel="stylesheet" href="http://libs.cartocdn.com/cartodb.js/v2/themes/css/cartodb.ie.css" />
<![endif]-->
<style>
html, body {width:100%; height:100%; padding: 0; margin: 0;}
#cartodb-map { width: 80%; height:100%; background: black; position:relative; z-index: 3; display:inline-block}
#parkList{
display:inline-block;
float:left;
width:20%;
z-index: 20000;
}
li{
width:30em;
}
</style>
<script>
var map;
function init(){
// initiate leaflet map
map = new L.Map('cartodb-map', {
zoom: 10,
center: [32.902222, -116.979378],
})
L.tileLayer('https://api.mapbox.com/v4/mapbox.outdoors/{z}/{x}/{y}.png?access_token='
+ 'pk.eyJ1IjoibXBtY2tlbm5hOCIsImEiOiJfYWx3RlJZIn0.v-vrWv_t1ytntvWpeePhgQ',
{
attribution: 'Mapbox <a href="http://mapbox.com/about/maps" target="_blank">Terms &amp; Feedback</a>'
}).addTo(map);
var layerUrl = 'http://mpmckenna8.cartodb.com/api/v2/viz/bf965a6a-486a-11e5-a399-0e018d66dc29/viz.json';
cartodb.createLayer(map, layerUrl)
// .addTo(map)
.on('done', function(layer) {
layer.addTo(map);
})
.on('error', function(err) {
console.log('there was a error', err) //log the error
});
var sql = new cartodb.SQL({ user: 'mpmckenna8', options:{
format:'GeoJSON'
} });
var parksSearch = [];
var options = {
item:'parkit',
}
console.log('trying to do a query')
sql.execute("SELECT DISTINCT ON (unit_name) unit_name, cartodb_id FROM parksinfo ORDER BY unit_name;")
.done(function(data) {
console.log(data.rows);
var parkli;
for( i in data.rows ){
parkli = data.rows[i];
// console.log($('.parksList'));
if (parkli.unit_name){
parksSearch.push(
{
parkname: parkli.unit_name,
id: parkli.cartodb_id,
})
// $('#parkList').append('<li>' + parkli.unit_name + '</li>')
}
}
// searchStart();
var parkli = new List('parkList', options, parksSearch);
})
.error(function(errors) {
// errors contains a list of errors
console.log("errors:" + errors);
})
}
</script>
</head>
<body onload="init()">
<div id='cartodb-map'></div>
<div id="parkList">
<ul class="list">
</div>
</ul>
<div style="display:none;">
<!-- A template element is needed when list is empty, TODO: needs a better solution -->
<li id="parkit">
<p class="parkname"></p>
</li>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment