This example shows how to create a Leaflet map with a basemap and an empty CartoDB.js layer. Once the layer is created a function is attached the event of the layers selector checkboxes so on any state change, the sublayers are removed and recreated according to the user selection.
xxxxxxxxxx
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title></title>
<link rel="shortcut icon" href="https://cartodb.com/assets/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://libs.cartocdn.com/cartodb.js/v3/3.14/themes/css/cartodb.css" />
</head>
<body>
<div id="map"></div>
<aside class="layers">
<h2>Layers</h2>
<ul>
<li class="layer">
<input type="checkbox" id="nucleos" name="layer">
<label for="nucleos">Núcleos</label>
</li>
<li class="layer">
<input type="checkbox" id="rios" name="layer">
<label for="rios">Ríos</label>
</li>
<li class="layer">
<input type="checkbox" id="aloja" name="layer">
<label for="aloja">Alojamientos</label>
</li>
</ul>
</aside>
<script src="https://cartodb-libs.global.ssl.fastly.net/cartodb.js/v3/3.14/cartodb.js"></script>
<script>
$( document ).ready(function() {
//Create the leaflet map
var map = L.map('map', {
zoomControl: true,
center: [39.583,2.670],
zoom: 12
});
var basemap = L.tileLayer('https://{s}.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, © <a href="https://cartodb.com/attributions">CartoDB</a>'
}).addTo(map);
// Layers definition
var layers = {
'nucleos': {
sql: 'SELECT * FROM nucleos_pobl_btn100',
cartocss: '#layer{polygon-fill: #D6301D;polygon-opacity: 0.7;}'
},
'rios': {
sql: 'SELECT * FROM rios_btn25',
cartocss: '#rios_btn25{line-color: #2E5387;line-width: 2;line-opacity: 0.7;}'
},
'aloja': {
sql: 'SELECT * FROM aloj_ocio_btn100',
cartocss: '#aloj_ocio_btn100{marker-fill-opacity: 0.9; marker-line-color: #FFF; marker-line-width: 1.5; marker-width: 10; marker-fill: #3B007F; }'
}
}
// Empty layer
cartodb.createLayer(map,{
user_name: 'ignspaintest',
type: 'cartodb',
sublayers: []
})
.addTo(map)
.done(function(layer){
// When the layers inputs change fire this
$("input[name='layer']").change(function(){
// Clear the sublayers
layer.getSubLayers().forEach(function(sublayer){sublayer.remove()});
// For every check activated, add a sublayer
$.each($("input[name='layer']:checked"), function(){
layer.createSubLayer(layers[$(this).attr("id")]);
});
});
});
});
</script>
</body>
</html>
https://cartodb-libs.global.ssl.fastly.net/cartodb.js/v3/3.14/cartodb.js