Is there a way to click on any map *marker* and retrieve the marker's lat/lng (or array index)?

2,694 views
Skip to first unread message

JP Carter

unread,
Dec 1, 2015, 2:45:48 PM12/1/15
to Leaflet
Hi everyone,

After reading through the docs and searching around, I'm coming up empty-handed.

In short, I'd like to be able to keep a log of when users click individual markers (by keeping tabs of the lat/long, but a marker index ID would work as well, I suppose). Through something like the following, I can get lat/lng for all map clicks, but I can't see to get this working for marker clicks:

function onMapClick(e) {
console.log("You clicked the map at " + e.latlng.toString());
}

map.on('click', onMapClick);


Not sure if relevant or not, but my markers are built via a looped version of:
L.marker(
[51.941196,4.512291],
{
icon: L.AwesomeMarkers.icon({
icon: 'link',
prefix: 'glyphicon',
markerColor: 'red',
spin:true
})
}).addTo(map);

It seems that I'm missing something in my thinking, that this should be straight-forwarded in Leaflet.

Any suggestions or solutions? Thanks for your expertise!

JP

ghybs

unread,
Dec 2, 2015, 1:23:22 AM12/2/15
to Leaflet
Hi,

There should be no special difficulty in attaching a callback to marker(s) click event.
You would simply use `myMarker.on('click', callback);` like you did with the map.
You would also have to do that for every marker you want to log.

Another possibility would be to add all your markers into a Feature Group, so that you can attach the callback directly to that Group.
It will receive the click events from individual markers, and you can access the individual clicked feature using `event.layer`.

Demo: http://jsfiddle.net/ve2huzxw/74/

Hope this helps.
Reply all
Reply to author
Forward
0 new messages