How to identify Leaflet's Marker during a `popupopen` event?

喜夏-厌秋 提交于 2019-11-30 00:43:56

问题


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 the content 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 this id during the popupopen event?


回答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;
});



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




回答3:


To get the marker id, you can use this code:

map.on('popupopen', function(e) {
  var marker = e.popup._source.feature.properties.markerid;
});



回答4:


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>



来源:https://stackoverflow.com/questions/12701240/how-to-identify-leaflets-marker-during-a-popupopen-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!