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.