Skip to content

Instantly share code, notes, and snippets.

@ramiroaznar
Last active August 16, 2021 17:38
Show Gist options
  • Save ramiroaznar/6f35b75d9bdfdc72a9d9a0208af10763 to your computer and use it in GitHub Desktop.
Save ramiroaznar/6f35b75d9bdfdc72a9d9a0208af10763 to your computer and use it in GitHub Desktop.
Create layer, add two sublayers and get sublayers

How to use createLayer, add two sublayers and get them as variables for future uses. Click on "Open" and open the Developers Tools Console. It should display two objects for the two layers or CartoDBSubLayers. Based on Oriol's sublayers order cartodb createLayer block.

<!DOCTYPE html>
<html>
<head>
<title>createLayer + add two sublayers + get sublayers</title>
<link rel="shortcut icon" href="http://cartodb.com/assets/favicon.ico" />
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<style>
html, body, #map {
height: 100%;
padding: 0;
margin: 0;
}
</style>
<!-- include cartodb css -->
<link rel="stylesheet" href="http://libs.cartocdn.com/cartodb.js/v3/3.15/themes/css/cartodb.css" />
<!-- include cartodb.js library -->
<script src="http://libs.cartocdn.com/cartodb.js/v3/3.15/cartodb.js"></script>
</head>
<body>
<!-- define a map object-->
<div id="map"></div>
<script>
function main() {
// create leaflet map and define some properties
var map = L.map('map', {
zoomControl: false,
center: [43, 0],
zoom: 3
})
// add a base layer to map
L.tileLayer('http://tile.stamen.com/toner/{z}/{x}/{y}.png', {
attribution: 'Stamen'
}).addTo(map);
// add cartodb layer with one layer
cartodb.createLayer(map, {
user_name: 'oboix', // Required
type: 'cartodb', // Required
sublayers: [
{ // first sublayer is the one that is painted at the bottom
sql: "SELECT * FROM populated_places_test", // Required
cartocss: '#populated_places_test{marker-fill: #229A00; marker-allow-overlap: true;}', // Required
},
{ // second sublayer is painted above the previous sublayer
sql: "SELECT * FROM world_table", // Required
cartocss: '#world_table {polygon-fill: #3E7BB6;polygon-opacity: 0.7;line-color: #FFF;line-width: 0.5;line-opacity: 1;}' // Required
}
]
}).addTo(map)
.done(function(layer){
var layer0 = layer.getSubLayer(0); // declare a layer0 variable
console.log(layer0); // show in the console layer0
var layer1 = layer.getSubLayer(1); // declare a layer1 variable
console.log(layer1); // show in the console layer1
});
}
// load main() function
window.onload = main;
</script>
</body>
</html>
LICENSE#
This block appears to have no license. Please contact the author to request a license.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment