JJD
JJD

Reputation: 51804

How to get notified when an Leaflet LayerGroup is shown or hidden?

I want to get notified whenever the user clicks the "Cities" checkbox in the layer controls - which shows or hides the city markers in the linked example. Here is a JSFiddle to play around with.

Leaflet screenshot

I saw that LayerGroup derives some events from FeatureGroup. Please correct me if I am wrong: As far as I understand showing and hiding the markers is not the same as layeradd and layerremove?!

The input element holds no id to bind to:

<label>
    <input class="leaflet-control-layers-selector" type="checkbox" checked="">
    <span> Cities</span>
</label>

How can I be notified when the markers' visibility is toggled?

Upvotes: 2

Views: 2668

Answers (1)

Alexandru Pufan
Alexandru Pufan

Reputation: 1912

You could use jQuery to select the input element, using its class:

$('.leaflet-control-layers-selector').click(function(){
    alert('something')
});

Furthermore, if you have more than one layer, you can check if the map contains one layer when you click one of the checkboxes.

$('.leaflet-control-layers-selector').click(function(){
    if(map.hasLayer(cities)) alert('something');
});

UPDATE

You can also use map events overlayadd and overlayremove, like this:

map.on({
    overlayadd: function(e) {
        if (e.name === 'Cities') alert('added');
    },
    overlayremove: function(e) {
        if (e.name === 'Cities') alert('removed');
    }
});

Here's an updated JSFiddle of your example: http://jsfiddle.net/pufanalexandru/g54efr69/1/

Upvotes: 7

Related Questions