Detecting Layer Enable/Disable Within Control

- 1 answer

Ad

Requirement:

I need to be able to detect when a user manually clicks a layer on/off within a Leaflet's map controls.

Problem:

I've found the "overlayadd" and "overlayremove" events and have tried to attach my logic to those events, but they seem to also fire during direct "addLayer" and "removeLayer" calls that I have elsewhere in code. This is too general. I only care about when the user initiates the action.

I could attach listeners directly to the control checkbox elements and dig into the DOM to find the corresponding layer name but that's relying on their HTML structure a lot more than I'd like to, since they could change that on a whim.

Are there any events lurking more specific to L.control actions or a way hidden in the overlayadd/overlayremove event parameters to detect what triggered the action? ... or just some other way to accomplish this?

Thanks

Ad

Answer

Ad

When L.Control.Layers clickhandler fires it sets it's own "private" _handlingClick property to true:

var marker = new L.Marker([0, 0]);

var control = new L.Control.Layers(null, {
    'Marker': marker
}).addTo(map);

map.on('overlayadd overlayremove', function (e) {
    if (control._handlingClick) {
        // Executes only on input toggle, not on
        // map.addLayer(marker) or map.removeLayer(marker)
    }
});
Ad
source: stackoverflow.com
Ad