6

How do I detect a click on a layer and find out information about the layer that was clicked?

Currently I can do the usual binding a popup and adding a click handler on the layer:

L.geoJson(data.streets, {
    onEachFeature: function(feature, featureLayer) {

        featureLayer.bindPopup(feature.properties.name);

        featureLayer.on('click', function(e) {

            console.log('Layer clicked!', e);
        });
    ...

However the click handler on the layer doesn't give me any information about the layer, just the following:

containerPoint: o.Point
latlng: o.LatLng {
    lat: 50.804443085898185,
    lng: -1.089920997619629 
}
__proto__: Object
layerPoint: o.Point
originalEvent: MouseEvent
target: e
type: "click"
__proto__: Object

How can I get a reference to the layer it's clicking?

2 Answers 2

4

the layer is available from the event; in your case e.layer returns the layer

alternatively, you save the layer to a variable when you construct it with L.geoJson, then bind your click event later:

var streets = L.geoJson(data.streets, {
    onEachFeature: function(feature, featureLayer) {
        featureLayer.bindPopup(feature.properties.name);
    })
)}
streets.on('click', function(e) { console.log(e.layer) });

This might be better; as it is now, I think you are binding a click event to the layer for every feature, which is probably not what you want to do.

1
  • 1
    I don't get a layer returned, see above. I'm clicking on a polyline if that makes a difference.
    – Titan
    Nov 17, 2014 at 8:49
3

I was assigning layers to a featureGroup, I needed to put the click handler on the featureGroup in order to get a layer reference returned. Putting it on the individual layer didn't work.

1
  • Any chance you could share some code for this? Jan 28, 2019 at 22:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.