Per my previous question - here - how do I get the legend to toggle (I have it turned off now) in conjunction with toggling the cartodb layer via the leaflet layer control? Maybe adding it as a variable some way?

  var cdb_url = 'http://ovrdc.cartodb.com/api/v2/viz/52a89830-a8c1-11e4-b072-0e0c41326911/viz.json';
  cartodb.createLayer(map, cdb_url, {legends:false})
    .on('done', function(crashes) {
      var overlayMaps = {
        "Vehicle Crashes": crashes
      L.control.layers(baseMaps, overlayMaps, {collapsed: false}).addTo(map);
    .on('error', function(err) {
      alert("some error occurred: " + err);

1 Answer 1


I suggest setting up an empty object to hold the cartodb layers

var cdb_layers = {}

Then, each time you add a cartodb layer, on done(), update the object with a reference to the layer:

cdb_layers['crashes'] = layer;

This gives you the overlays structure you need to create the L.control.layers. Only construct the L.control.layers after all of your cartodb layers are loaded.

updated fiddle

  • Thanks, had to change my cdb layer - here is the new fiddle with the new layer jsfiddle.net/q5uy3bh2/5 - still doesnt answer the legend question though
    – Malcolm
    Feb 4, 2015 at 0:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.