Demonstrates loading data from a Carto table and creating a GeoJSON vector layer in a Leaflet Map.
Built with blockbuilder.org
license: mit |
Demonstrates loading data from a Carto table and creating a GeoJSON vector layer in a Leaflet Map.
Built with blockbuilder.org
<!DOCTYPE html> | |
<head> | |
<meta charset="utf-8"> | |
<!-- cartodb.js comes with Leaflet @0.7 and jQuery --> | |
<link rel="stylesheet" href="http://libs.cartocdn.com/cartodb.js/v3/3.15/themes/css/cartodb.css" /> | |
<script src="http://libs.cartocdn.com/cartodb.js/v3/3.15/cartodb.js"></script> | |
<!-- This script makes it easy to use Stamen basemaps --> | |
<script type="text/javascript" src="http://maps.stamen.com/js/tile.stamen.js?v1.3.0"></script> | |
<style> | |
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } | |
#map { | |
height: 100%; | |
} | |
</style> | |
</head> | |
<body> | |
<div id="map"></div> | |
<script> | |
// necessary for making AJAX calls on Blockbuilder.org as of 2016-11-02 | |
jQuery.support.cors = true; | |
// create a new map centered on the U.S. | |
var map = L.map('map').setView([39.69, -99.185], 5); | |
// create a tile layer for our toner basemap | |
var tonerLayer = new L.StamenTileLayer("toner-lite"); | |
// add the tile layer to the map | |
map.addLayer(tonerLayer); | |
// Set up our GeoJSON layer, add it to the map, but don't add data just yet | |
var tornadoLayer = L.geoJson(null).addTo(map); | |
// Here are two different ways to load data from a Carto table | |
/* | |
* Method 1: using jQuery's getJSON method | |
*/ | |
// the endpoint to make SQL calls to | |
var endpoint = "https://stamen-builder.carto.com/api/v2/sql?format=GeoJSON&q="; | |
// sample query for our Tornado table | |
var query = "SELECT * FROM tornado WHERE \"timestamp\" >= '2012-01-01' and \"timestamp\" < '2013-01-01'"; | |
// using getJSON we concatenate these two strings to create the target URL | |
var url = endpoint + query; | |
$.getJSON(url, function(data) { | |
console.log(data); | |
// add the tornado data to our tornadoLayer | |
// tornadoLayer.addData(data); | |
}) | |
.fail(function( jqxhr, textStatus, error ) { | |
var err = textStatus + ", " + error; | |
console.log( "Request Failed: " + err ); | |
}); | |
/* | |
* Method 2: using the cartodb.js SQL object | |
*/ | |
// set up the SQL object by giving it your Carto account name | |
// if you want to write to your table you'll also need to pass an API Key, | |
// eg: `api_key: 'someReallylongString'` | |
var sql = new cartodb.SQL({ user: 'stamen-builder' }); | |
// execute the query, first param is the SQL query string, | |
// second can be variables to be interpretted by the query, | |
// third are additional options | |
sql.execute(query, null, { format: 'geojson' }) | |
.done(function(data) { | |
console.log(data); | |
// add the tornado data to our tornadoLayer | |
tornadoLayer.addData(data); | |
}); | |
</script> | |
</body> |