Skip to content

Instantly share code, notes, and snippets.

@ramiroaznar
Last active August 8, 2016 13:35
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 ramiroaznar/ebf41884cff6c8cf60da623ee3296836 to your computer and use it in GitHub Desktop.
Save ramiroaznar/ebf41884cff6c8cf60da623ee3296836 to your computer and use it in GitHub Desktop.
createLayer + layerSource + IW with CARTO.js
<!DOCTYPE html>
<html>
<head>
<title>createLayer + layerSource + IW with CARTO.js</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" />
<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>
<style>
html, body, #map {
width:100%;
height:100%;
padding: 0;
margin: 0;
</style>
</head>
<body>
<div id='map'></div>
<script>
function main() {
// declare a map object
var map = new L.Map('map', {
center: [40, 0],
zoom: 4
});
// add basemap
L.tileLayer('http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', {
attribution: 'CartoDB'
}).addTo(map);
var query = 'select * from populated_places';
var style = '#layer{marker-fill: red; marker-width: 5; line-width: 0;}'
var markersLayerSource = {
user_name: 'ramirocartodb',
type: 'cartodb',
sublayers: [{
sql: query,
https: 'force https',
cartocss: style,
interactivity: 'cartodb_id, pop_max, name'
}]
}
// add layer
cartodb.createLayer(map, markersLayerSource, {https:true})
.addTo(map)
// add sublayer
.done(function(layer) {
var cartoLayer = layer.getSubLayer(0);
cartoLayer.setInteraction(true);
cartoLayer.on('featureOver', function(e, pos, pixel, data) {
// print data to console log
console.log("Event #" + data.cartodb_id + ", name " + data.name + ", max population: " + data.pop_max);
});
var tooltip = layer.leafletMap.viz.addOverlay({
type: 'tooltip',
layer: layer,
template: '<div class="cartodb-tooltip-content-wrapper"> <div class="cartodb-tooltip-content"><h3>{{name}}</h3><p>{{pop_max}} inhabitants</p></div></div>',
width: 200,
position: 'bottom|right',
fields: [{ name: 'name' }, { pop_max: 'pop_max' }]
});
$('body').append(tooltip.render().el);
});
}
window.onload = main;
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment