11

I have multiple base layers, and need to switch them programmatically, dependent on various actions and states in my application. Can't find how, for the life of me.

15

This tutorial serves as a good example:

1) As shown in the example, set up your base layers with a variable name that can be accessed in the function where you want to switch them programmatically.

var grayscale = L.tileLayer(mapboxUrl, {id: 'MapID', attribution: mapboxAttribution}),
    streets   = L.tileLayer(mapboxUrl, {id: 'MapID', attribution: mapboxAttribution});

2) Then add and remove the layers you want to add or remove. The following swaps the grayscale layer for the streets layer. This assumes that both grayscale and streets are available within the scope of the function where you are doing the switching.

map.removeLayer(grayscale);
map.addLayer(streets);

3) If you are using the layers control L.control.layers shown in the example, then the control keeps track of what is on the map, and changes the checkboxes accordingly.

0

From https://stackoverflow.com/a/33762133/4355695

Normally by simply adding a layer to the map (e.g. myTileLayer.addTo(map)), if that layer is part of the base layers or overlays of the Layers Control, the latter will automatically update its status (if you added a base layer, the radio buttons will be selected accordingly; for an overlay, the corresponding checkbox will be ticked).

I tried and it worked: I don't need to bother with removing the current baselayer (or with figuring out which one's active for that matter). Just myTileLayer.addTo(map) does the job : If it is already part of my baselayers, then the map "switches" to it. It automatically removes the current layer and changes to myTileLayer.

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.