2

I'm trying to use leaflet layergroups with a cartodb layer, ala: http://leafletjs.com/reference.html#layergroup but haven't been able to successfully do it.

This is what I have so far:

    var map = new L.Map('map', {
      zoomControl: true,
      center: [41.460, -81.67],
      zoom: 11
    });

    map.locate({setView: true, maxZoom: 18});

    var background = L.tileLayer('http://{s}.tile.stamen.com/toner-lite/{z}/{x}/{y}.png', {
      attribution: 'Stamen',
      maxZoom: 15,
      errorTileUrl: 'http://fashiontech.files.wordpress.com/2008/08/plaid_b_single.jpg?w=256'
    })
     .setZIndex(0),

    cdb = cartodb.createLayer(map, 'http://cleveland-metroparks.cartodb.com/api/v2/viz/05af5a7c-668d-11e3-8914-cb7f69afe66f/viz.json')

     .on('done', function(layer) {

      layer.setInteraction(true);

      layer.on('featureOver', function(e, pos, latlng, data) {
        cartodb.log.log(e, pos, latlng, data);
      });

      layer.on('error', function(err) {
        cartodb.log.log('error: ' + err);
      });
    }).on('error', function() {
      cartodb.log.log("some error occurred");
    }),

    labels = L.tileLayer('http://{s}.tile.stamen.com/toner-labels/{z}/{x}/{y}.png', {
      attribution: 'Stamen',
      maxZoom: 18
    })
     .setZIndex(600);

    var existing = L.layerGroup([background, cdb]);
    var baseLayers = {
        "Existing": existing
    };        

    L.control.layers(baseLayers).addTo(map);

This answer hints that it's possible, but my js-fu is really lacking: How does Leaflet layer ordering work with CartoDB layers?

0

1 Answer 1

1

cartodb.createLayer does not return a leaflet layer, you need to use the layer passed in the 'done' callback.

Moving the control creation inside the 'done' callback will do the trick

2
  • So do you mean add the layer switcher control to the done callback? Commented Apr 22, 2014 at 13:22
  • Yes, you need to user the layer object you get in the callback Commented Apr 22, 2014 at 13:53

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.