Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture a click on a specific leaflet layer

I think the question says it all. I am using leaflet. I am loading three layers onto the map.

However I can't find a way to know on which layer I clicked after clicking on the map. Basically because there is no event handler set on layers, only onto the map.

I also tried to add the layers into a feature group and add an on click event to this feature group. However clicking on the map does not result in any event / response.

This is what I did in the featureGroup:

addWaterNameLayers: function() {

    var knownWaters = L.tileLayer.wms(getGeoServer('wms', geoEnviroment), {
        layers: this.wmsLayers.known.name,
        format: 'image/png',
        opacity: 0,
        styles: 'cursor: pointer',
        transparent: true,
        attribution: ""
    });//.addTo(this.mapInfo);

    var unknownWaters = L.tileLayer.wms(getGeoServer('wms', geoEnviroment), {
        layers: this.wmsLayers.unknown.name,
        format: 'image/png',
        opacity: 0.3,
        styles: '',
        transparent: true,
        attribution: ""
    });

    L.FeatureGroup(knownWaters, unknownWaters).on('click', function(event) {
       console.log('click');
       this.handleClick(event);
    },this);

    //this part will work on mapclick, so on featuregroup it should work?
    //when clicking on the map
    /*
    this.mapInfo.on('click', function(event) {
        this.handleClick(event);
    }, this);
    */

},

in the code above you can see the click event on te map as well... that one works. on the featuregroup it doesn't.

Also when I change the code for the featureGroup to these it will not work either:

    var featGr = L.FeatureGroup(knownWaters, unknownWaters).on('click', function(event) {
       this.handleClick(event);
    },this);


    var featGr = L.FeatureGroup(knownWaters, unknownWaters);
    featGr.on('click', function(event) {
       this.handleClick(event);
    },this);

adding the featureGroup to the layer will also do nothing...

like image 578
BonifatiusK Avatar asked Sep 06 '25 13:09

BonifatiusK


2 Answers

Put your layers in L.FeatureGroup. L.FeatureGroup is an extension of L.LayerGroup which adds events. It also supports the clickevent so that's exactly what your are looking for. Check the documentation: http://leafletjs.com/reference.html#featuregroup

like image 157
iH8 Avatar answered Sep 09 '25 03:09

iH8


event.layer is layer data

event.originalEvent.path[0]

is element you clicked

like image 24
thinhnk Avatar answered Sep 09 '25 05:09

thinhnk