Search code examples
javascriptleaflet

LeafletJS - Default selection of layers


I'm using leaflet-groupedlayercontrol to add my grouped layers to the map and I have a problem:

All the layers are deselected, but I want to select all by default. I am using checkboxes, not radio buttons.

var groupedOverlays = {
    "Select": {}
};

groupedOverlays["Select"]["Group 1"] = groups[0];
groupedOverlays["Select"]["Group 2"] = groups[1];
groupedOverlays["Select"]["Group 3"] = groups[2];

// Use the custom grouped layer control, not "L.control.layers"
L.control.groupedLayers(null, groupedOverlays, {collapsed:false}).addTo(map);

I tried to select them with JS, but didn't worked.

If you know a solution for LeafletJS, but not for that particular plugin, it's ok too.


Solution

  • Whether a Leaflet layer is ""selected"" or not in the built-in L.Control.Layers depends on whether the layer is added to the map or not.

    e.g. this will display a L.Control.Layers with the checkbox off:

    L.control.layers({}, { 
        Foo: L.marker([0,0]) 
    }).addTo(map)
    

    ...while this will display it with the checkbox on:

    L.control.layers({}, { 
        Foo: L.marker([0,0]).addTo(map)
    }).addTo(map)
    

    I expect the behaviour of the GroupedLayers control to be similar. Just double-check whether you add the layers to the map or not. Also notice that the checkboxes' state updates whenever layers are added/removed to/from the map by any means, at any time.