Skip to content

Instantly share code, notes, and snippets.

@ramiroaznar
Last active February 3, 2017 11:54
Show Gist options
  • Save ramiroaznar/b92751b7082b980499c605afcb8f4a51 to your computer and use it in GitHub Desktop.
Save ramiroaznar/b92751b7082b980499c605afcb8f4a51 to your computer and use it in GitHub Desktop.
How to store and paint data with CARTO and Leaflet
<!DOCTYPE html>
<html>
<head>
<title>How to store and paint data with CARTO and Leaflet</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="https://cartodb-libs.global.ssl.fastly.net/cartodb.js/v3/3.15/themes/css/cartodb.css" />
</head>
<body>
<div id="map"></div>
<!-- include cartodb.js library -->
<script src="https://cartodb-libs.global.ssl.fastly.net/cartodb.js/v3/3.15/cartodb.js"></script>
<script type="text/javascript">
function main() {
// create map object
var map = L.map('map', {
zoomControl: false,
center: [41, -3],
zoom: 3
});
// add basemap
L.tileLayer('http://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}.png', {attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, &copy; <a href="http://cartodb.com/attributions">CartoDB</a>'}).addTo(map);
// add layer
cartodb.createLayer(map, {
user_name: 'ramirocartodb',
type: 'cartodb',
sublayers: [{
sql: "select * FROM populated_places;",
cartocss: "#layer{polygon-fill: ramp([pop2005], (#f3e79b,#fac484,#f8a07e,#eb7f86,#ce6693,#a059a0,#5c53a5), quantiles(7)); polygon-opacity: 0.7; line-color: gray; line-width: 0.3; line-opacity: 0.9; polygon-gamma: 0.5;}",
}]
}).addTo(map)
.done(function(layer){
var sql = new cartodb.SQL({ user: 'ramirocartodb' });
var points = []; // create geoJson array object
var pointsJson = []; // create json array object
var id = []; // create field arrays objects
var city = [];
var pop = [];
var geom = [];
sql.execute("SELECT *, ST_asGeoJSON((ST_Dump(the_geom)).geom) as geom FROM populated_places WHERE pop_max > 5000000 ORDER BY pop_max DESC")
.done(function(data){
for(i = 0; i < data.total_rows; i++){ // loop that reads each column of the table
id[i] = data.rows[i].cartodb_id;
city[i] = data.rows[i].name;
pop[i] = data.rows[i].pop_max;
geom[i] = data.rows[i].geom;
points = L.geoJson(JSON.parse(geom[i]), {population: pop[i]}).addTo(map); //populate geoJSON and paint it with Leaflet
pointsJson.push({ // populate json
id: id[i],
city: city[i],
geometry: geom[i],
population: pop[i]
});
}
console.log(pointsJson[0]); // show 1st element
});
});
}
window.onload = main;
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment