2

I'm trying to build an interactive game map with Leaflet and I would like to implement nested layer groups. I tried doing it the obvious way: putting some layer groups inside of a "master" layer group, and that does kinda work, but the control won't work with it even if I write custom event handlers. I spent the past hour looking into the source of Leaflet trying to understand why this won't work, but I can't figure it out.

// Load markers
const overlay_materials = {};
const materials_lg = L.layerGroup();
overlay_materials["Materials"] = materials_lg;

for(let key in markers['materials']) {
    let material = markers['materials'][key];
    let layerGroup = L.layerGroup();
    for(let coords in material['coords']) {
        coords = material['coords'][coords];
        layerGroup.addLayer(
            L.marker(coords, {
                icon: L.icon({
                    iconUrl: markers['icon_base'] + material['icon'],
                    iconSize: material['size']
                }),
                title: key,
                alt: key
            }));
    }

    materials_lg.addLayer(layerGroup);
    overlay_materials[key] = layerGroup;
}

materials_lg.addTo(map);

// Add control for layers
L.control.layers(null, overlay_materials, {
    collapsed: false
}).addTo(map);

materials_lg.on('add', e => {
    materials_lg.eachLayer(lg => {
        map.addLayer(lg);
    })
});

materials_lg.on('remove', e => {
    console.log("Removed");
    materials_lg.eachLayer(lg => {
        console.log(lg);
        map.removeLayer(lg);
    })
});

If all the sub layers groups are not selected it does work fine, but it does not update the control checkboxes, so if one of the other layer groups is selected it won't work as expected.

Vince
  • 20,017
  • 15
  • 45
  • 64
Leo
  • 21
  • 3
  • 1
    For reference: https://gis.stackexchange.com/questions/230675/leaflet-v1-plugin-layer-control-for-ungrouped-grouped-and-nested-grouped-laye (one of the unanswered question with the highest number of votes) – StefanBrand_EOX May 15 '20 at 22:16
  • 2
    See also https://leafletjs.com/plugins.html#layer-switching-controls – IvanSanchez May 16 '20 at 01:58
  • From your question it's not clear what you are trying to achieve. A picture or two and description of desired behavior would help. – TomazicM May 16 '20 at 07:02

0 Answers0