Programatically change selected base layer

4,091 views
Skip to first unread message

cathal coffey

unread,
Jun 19, 2014, 2:29:36 AM6/19/14
to leafl...@googlegroups.com
I have 3 different baseMaps in my layers control. How can I programatically change the selected baselayer?
I am looking for something like
map.setBaseLayer(floor_2);
control.setSelected(2);

var baseMaps = {
            "Floor 1": floor_1,
            "Floor 2": floor_2,
            "Floor 3": floor_3
         };

control = L.control.layers(baseMaps, {}, {collapsed: false});
control.addTo(map);


Kind regards,
Cathal

Historical Atlas

unread,
Jun 19, 2014, 6:07:59 AM6/19/14
to leafl...@googlegroups.com
Hi,

just add the layer (will also change layerControl
map.addLayer(floor_2);
--

---
You received this message because you are subscribed to the Google Groups "Leaflet" group.
To unsubscribe from this group and stop receiving emails from it, send an email to leaflet-js+...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

cathal coffey

unread,
Jun 19, 2014, 7:02:25 PM6/19/14
to leafl...@googlegroups.com
If map.addLayer(layer) is the correct way to switch the active layer then why does the following not end up with floor_1 as the active later?

Historical Atlas

unread,
Jun 20, 2014, 4:20:26 AM6/20/14
to leafl...@googlegroups.com
Hi Cathal,

Yes you are right, I probably should have tried moving back up the base-layer tree.  Problem is, you need to remove existing layers from the map, or else the you won't be able to switch back to floor 2 or 1 (at least programmatically). Note that when layers are switched via layer-control leaflet uses this code (from the souce):
           
            if (input.checked && !this._map.hasLayer(obj.layer)) {
                this._map.addLayer(obj.layer);

            } else if (!input.checked && this._map.hasLayer(obj.layer)) {
                this._map.removeLayer(obj.layer);
            }

So you would have to write a function that takes care of removing the other active baselayers from the map (for example by looping them in your baselayer object, something like this:

function switchLayer(destLayer) {
    for (var base in baseLayers) {
        if (map.hasLayer(baseLayers[base]) && baseLayers[base] != destLayer) {
            map.removeLayer(baseLayer[base]);
        }
    }
    map.addLayer(destLayer);
};

Using the function things should work as expected.

Cheers




On 06/20/2014 01:02 AM, cathal coffey wrote:
If map.addLayer(layer) is the correct way to switch the active layer then why does the following not end up with floor_1 as the active later?

cathal coffey

unread,
Jun 20, 2014, 5:41:06 AM6/20/14
to leafl...@googlegroups.com
You have a small typo but other than that this works perfectly, thank you.
map.removeLayer(baseLayers[base]); 

Updated fiddle for those who may follow.
Reply all
Reply to author
Forward
0 new messages