How to capture a click on a specific leaflet layer

12,831

Solution 1

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

Solution 2

event.layer is layer data

event.originalEvent.path[0]

is element you clicked

Share:
12,831
BonifatiusK
Author by

BonifatiusK

Updated on June 27, 2022

Comments

  • BonifatiusK
    BonifatiusK almost 2 years

    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...