How to switch base layer programmatically in MapBox/Leaflet
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.