How to identify Leaflet's Marker during a `popupopen` event?
Solution 1
The event object contains a "popup" attribute that has a private attribute called "_source" which is the object that the popup is bound to (i.e. the marker). Since _source is supposed to be private this doesn't seem like the right way but I'm not sure how else to do it.
map.on('popupopen', function(e) {
var marker = e.popup._source;
});
Solution 2
Javascript objects can have any properties defined on them. Set popup.marker to the referenced marker when you create the popup. Then you can access it later in the event handler.
Solution 3
Other answers didn't work, but this does:
map.on('popupopen', function(e) { alert(e.popup._source._popup._content); });
Guess this library is pretty volatile ...and I'm not sure why it's this complicated to transmit such information in the first place. <shrug>
Solution 4
To get the marker id, you can use this code:
map.on('popupopen', function(e) {
var marker = e.popup._source.feature.properties.markerid;
});
Related videos on Youtube
Nyxynyx
Hello :) I have no formal education in programming :( And I need your help! :D These days its web development: Node.js Meteor.js Python PHP Laravel Javascript / jQuery d3.js MySQL PostgreSQL MongoDB PostGIS
Updated on July 09, 2022Comments
-
Nyxynyx almost 2 years
when a marker is clicked, I need to execute some code that finds the
id
corresponding to the marker being clicked , retrieves data from backend API, then adds the newly retrieved data to thecontent
of the popup that will open.The only way that is able to listen to a click event on the marker is
map.on('popupopen', function(e){ // How to retrieve marker? // eg: Assign an id on creation, retrieve it now during popupopen };)
How can I find out which marker this is? Is it possible to add an
id
attribute to each marker, then retrieve thisid
during thepopupopen
event?-
Nyxynyx over 11 yearsleaflet.cloudmade.com/reference.html#marker A
L.Marker
is placed on the map:marker.addTo(map)
. I am able to pass anid
value to each individualmarker
object. How should this be done, and how can I retrieve thisid
later during apopupopen
event? -
Nyxynyx over 11 yearsWhen creating markers, I do something like
var marker = new L.marker( new L.LatLng( lat, lng ));
Thenmarker.setContent(content).addTo(map)
.
-
-
Nighto almost 9 yearsI'm getting
undefined
one.popup._source
when opening a popup that was generated by aL.geoJson()
call. Any clues? -
Nighto almost 9 yearsMy dirty solution on the moment was to include a
<div>
inside the popup content ononEachFeature
and then looking it up on...e.target._popup._contentNode.childNodes[0].attributes[0]
. Yeah, dirty, but it works. phew -
Léo about 8 yearsExcellent Idea, because in my case
e.popup._source
wasnull
-
Roberto about 4 yearsThis answer is arguable better than the accepted one, since the
e.popup._source
can indeed be missing, for instance if the popup was opened/closed programmatically (instead of clicking).