1

Is there a good way to change leaflet basemaps from cartodb.js or leaflet.js? I am able to grab the map object and basemap layer from the layers property in the done() promise.

cartodb.createVis(map, layerUrl, mapOptions)
      .done(function(vis, layers) {
          var map = vis.getNativeMap();
          var basemap = layers[0];
      })
      .error(function(err) {
        console.log("An error occurred: " + err);
      });

Right now I'm thinking I need to be able to grab tileLayer from the basemap object or the map object, then use leaflet's setUrl method as per http://leafletjs.com/reference.html#tilelayer-seturl, but so far no luck there.

0

Yeah, really close, you'll need to set it on the basemap, which is actually layer[0], when you are using createVis at least. So here is how it would work,

cartodb.createVis('map', layerUrl)
  .done(function(vis, layers) {
      var basemap = layers[0];
      basemap.setUrl('http://{s}.tile.osm.org/{z}/{x}/{y}.png');
  })
  .error(function(err) {
    console.log("An error occurred: " + err);
  });

Of course, if you want to reference basemap outside the done promise, make sure it has a different scope. Otherwise you should be set.

If your visualization in CartoDB didn't have a basemap, you would need to add one to your layers instead of just updating layer[0].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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