[GIS] Adding and remove layers in cartodb

carto

I've been trying to follow the documentation for cartodb for a while to figure this out, but haven't found it very clear. All I'm trying to do is hide one layer and then show another layer upon button click.

However, I have no idea of the syntax and the documentation wasn't much help.

$(document).ready(function() {

var map2 = new L.Map('attribute_map', { 
center: [39.8282,-98.5795],
zoom: 4,

})
var map2;
$('#load_2').click(function() {

$('#load_2').css("display","none");
$ ('#attribute_map').css("height","520px");


 var mapURL = 'https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_nolabels/{z}/{x}/{y}.png'
L.tileLayer(mapURL, {

}).addTo(map2);
 cartodb.createLayer(map2, 'https://jonmrich.cartodb.com/api/v2/viz/50366df6-afed-11e4-ab33-0e853d047bba/viz.json', { https: true,legends: true,cartodb_logo:false,layerIndex:1 })
.addTo(map2)

});
$('#load_3').click(function() {

 cartodb.createLayer(map2, 'https://jonmrich.cartodb.com/api/v2/viz/0a63ff26-ad47-11e4-bebb-0e4fddd5de28/viz.json', { https: true,legends: false,cartodb_logo:false, })
.addTo(map2)
 });
  });

Can someone point me in remotely the right direction? In this example, I'm trying to add visualizations based on different tables. I also tried doing it for multiple layers in the same visualization, but couldn't figure that out either.

Best Answer

You should load both sublayers through createLayer, then turn off the one you want to hide initially.

The following works if you have two tables in the visualization you created in CartoDB Editor. If you want to add layers without having a viz.json link, you can create the layers at runtime.

// Instantiate map
var map = L.map('map', { 
            center: [39.8282,-98.5795],
            zoom: 4
           });

// basemap url
var mapURL = 'https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_nolabels/{z}/{x}/{y}.png'

// add basemap tiles to map
L.tileLayer(mapURL, {
        attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, &copy; <a href="http://cartodb.com/attributions">CartoDB</a>'
    }).addTo(map);

// add cartodb data layers to map
cartodb.createLayer(
    map, 
    'https://jonmrich.cartodb.com/api/v2/viz/50366df6-afed-11e4-ab33-0e853d047bba/viz.json', 
    {
        https: true,
        legends: true,
        cartodb_logo:false,
        layerIndex:1 
    })
.addTo(map)
.done(function(layer) { // when successful, do this stuff

    var sublayer0 = layer.getSubLayer(0);
    var sublayer1 = layer.getSubLayer(1);

    // hide sublayer1
    sublayer1.hide();

    $("#load_3").on('click', function() { 
    // turn on layer off, turn off layer on
        sublayer0.toggle();
        sublayer1.toggle();
    });
})
.error(function(err) { // when error, do this
    console.log("error: " + err);
});
Related Question