How to change base layer using JS and leaflet layers control

user3523426 picture user3523426 · Nov 17, 2015 · Viewed 11.6k times · Source

I have to modify existing application, where leaflet layers control is used - I need to display one of the base layers when the map is initiated. Is there a way, how to call some function from the layers control from JS script - something like control.select(1) ....? If not, how can add a tile layer in the same way as it is done by the control - when I add new L.TileLayer during map init, it's not overwritten by manual layers control selection change?

Answer

ghybs picture ghybs · Nov 17, 2015

You could try to emulate a user click on the Leaflet Layers Control, but there is a much more simple way to achieve what you initially describe.

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).

Now I am not sure I understood properly your last part ("when I add new L.TileLayer during map init, it's not overwritten by manual layers control selection change").

If you mean you have an unexpected behaviour because the Tile Layer you added is not changed by the Layers Control, it may be due to the fact that you are not re-using a Tile Layer that the Layers Control knows: do not use new L.TileLayer, but re-use one of the base layers or overlays.

For example:

var baselayers = {
    "Tile Layer 1": L.tileLayer(/* ... */),
    "Tile Layer 2": L.tileLayer(/* ... */),
    "Tile Layer 3": L.tileLayer(/* ... */)
};

var overlays = {};

L.control.layers(baselayers, overlays).addTo(map);

baseLayers["Tile Layer 1"].addTo(map);