leafletjs how to get a handle to the active pop/ma

2019-03-06 00:27发布

问题:

I am want to be able to change the content of a popup on a leafletjs map. I have have hundreds of markers each with their own popup, they are loaded in a for loop from an array.

    var marker = L.marker(new L.LatLng(a[0], a[1]), { title: title });
    marker.bindPopup('<img width="'+width+'" height="'+height+'"  src="'+a[3]+'"/><br><div id="weather"> <button type="button" onclick="weatherload(\''+a[0]+'\',\''+a[1]+'\')">Click Me for Weather!</button></div>',{'maxWidth':'500','maxHeight':'350','minWidth':'350'});
    CAMlayer.addLayer(marker);

That makes a popup with a picture and a button. When the button is clicked I want the button to go away being replaced by a loading gif. While an AJAX function asks the sever for a few things, once it gets the data from the sever, it should change content again. I can do all of that with the id on the div, but that breaks the re-sizing of the popup, which I would like to work.

myPopup._updateLayout()

can be used to force it to resize, but how do I tell it which is myPopup to work on?

I understand setContent is the proper way to update the popup, but again, how do I tell it which popup is the active one that I want to work on?

How to identify Marker during a popupopen event? That looks promising, but I have not figured out how to use the id that is set that way to change the popup content.

for grammar.

回答1:

You would have several options to keep a reference to the popup in which the clicked button is contained.

They "easy" one (for your case where you fill the popup content with plain HTML text, including your button HTML) would be to keep a mapping of each popup / marker, with the keys being a kind of ID, then pass that ID to your weatherload function.

If you keep a reference to the marker only, you can retrieve the bound popup using getPopup() method.

var allMarkersMap = {};
var currentID = 0;

// Create a marker with a popup.
var button = '<button onclick="weatherload('+ lat + ',' + lng + ',' + currentID + ')">Click Me for Weather!</button>';
var marker = L.marker(lat, lng).bindPopup(permanentContent + button);
marker.myPermanentContent = permanentContent;

allMarkersMap[currentID] = marker;
currentID += 1;

// Loop to create more markers.

function weatherload(lat, lng, markerID) {
  var marker2 = allMarkersMap[markerID];
  var permanentContent2 = marker2.myPermanentContent;
  var popup = marker2.getPopup();
  // Use this to add your loading GIF. Do the same in your AJAX callback.
  popup.setContent(permanentContent2 + newContent);
}

A more complex solution (but which gives you more control) would be to create the HTML elements that will be in your popup. That way, you can directly bind your popup as a property of your button.

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