23

All, I want to detect user layer selection in order to synchronize my sidebar with the displayed layers.

But I don't see any layer control events in the API reference; How might I tell when such user layer selection has occurred?

As an alternative, I've looked at the layer load and unload events, but I don't see any identification in what's returned. Did I miss that somehow?

user1032402
  • 410
  • 1
  • 3
  • 11

4 Answers4

38

There are some events that let you know when the user activates / desactivates a layer.

This may help you:

https://leafletjs.com/reference-1.4.0.html#map-baselayerchange

For example:

map.on('overlayadd', onOverlayAdd);

function onOverlayAdd(e){
    //do whatever
}
Mark McClure
  • 4,862
  • 21
  • 34
Adrian Garcia
  • 788
  • 10
  • 14
34

There is a "baselayerchange' event defined here http://leafletjs.com/reference.html#control-layers Just bind it to the map object and you are good to go.

map.on('baselayerchange', function(e) {
  console.log(e);
});
Mikko Viitala
  • 8,344
  • 4
  • 37
  • 62
Jabran Saeed
  • 5,760
  • 3
  • 21
  • 37
0

You may bind your own "change" event to the Leaflet layers control radio buttons with jQuery like this:

    $("[name='leaflet-base-layers']").change( function () {
        alert('Layers selected: ' + $(this).parent().text());
    });
Etienne Desgagné
  • 3,102
  • 1
  • 29
  • 36
  • I was hoping I cd use the native Leaflet, non-JQuery layers control, but I'm beginning to suspect that it's not possible. Re which kind of layer, I'll be pleased with whatever is available. – user1032402 Jan 11 '13 at 21:27
0

I haven't actually tried to use it yet, but this plugin looks promising: https://github.com/vogdb/Leaflet.ActiveLayers

I'm going to give it a shot in one of my projects because this is a very useful function.

ChidG
  • 3,053
  • 1
  • 21
  • 26