Reputation: 854
I have a feature group containing several markers.
And I have this code to respond to a click on any of the markers:
sampleFeatureGroup.on("click", function(){
alert(this.id); // something like this
});
I want to be able to get the id of the marker which is clicked on from within the function, however "this" refers to the feature group, so I cannot find the id of the marker clicked on, this seems like it should be easy but I can't figure it out.
Upvotes: 3
Views: 13751
Reputation: 9633
Although it is possible to retrieve the ID using this._leaflet_id
, this is not best practice because variables prefixed with _
should be treated as private.
Instead, it would be better to use the getLayerId()
function like below:
group.eachLayer(function(layer) {
layer.on('click', function(){
alert(group.getLayerId(layer))
});
});
Upvotes: 6
Reputation: 1912
You must use eachLayer
to iterate through the featureGroup, and then bind a function to the click event, like this:
group.eachLayer(function(layer) {
layer.on('click', function(){
alert(this._leaflet_id)
});
});
Here's a working example on Plunker: http://plnkr.co/edit/4fh7vhVet8N0iD4GE3aN
And here's the reference to eachLayer
:
http://leafletjs.com/reference.html#layergroup-eachlayer
Upvotes: 6