Fabrizio Mazzoni Fabrizio Mazzoni - 4 months ago 117
Javascript Question

leaflet.js check if a marker has its bound popup open

As per subject how can I check if a marker has a popup open?

eg.

var m = new L.marker([2,1]).addTo(map).bindPopup('test');


Clicking on the marker will obviously open the popup.

Is there any functionality such as:

if(m.popupOpen() == true) {
// do somehting
}


I have tried the following:

m.on('click', function(e) {
if(m._map.hasLayer(m._popup)) {
// Do something
}
}


But it's very flaky. On chrome it will run, on android browser if will fire on the second click so it is not really reliable.

Is there any standard way of doing this?

Thanks

iH8 iH8
Answer

You could do a quick and dirty check on the _isOpen property of the _popup object contained within L.Marker:

var map = L.map('map').setView(L.latLng(0, 0), 0);
var marker = L.marker(L.latLng(0, 0)).addTo(map);
marker.bindPopup("Popup!");
var popup = marker.getPopup(); // returns marker._popup

console.log(popup._isOpen); // false

marker.openPopup();

console.log(popup._isOpen); // true

marker.closePopup();

console.log(popup._isOpen); // false

Edit: v1.0.0 L.Popup has an isOpen method:

http://leafletjs.com/reference-1.0.0.html#popup-isopen