4
votes

I have multiple (444) popups open on my map.

I tried this:

$(".leaflet-popup-close-button").each(function (index) {
    $(".leaflet-popup-close-button")[index].click();
});

But this way, not all get closed. Only half of them get removed. Exactly half. So first time 222 get removed, the second time 111 get removed.

Why is this happening?

3
Create a fiddle reproducing the problem. It's hard to provide an answer based on you have.Adam Azad
$(this).click()vp_arth

3 Answers

0
votes

I see what you're trying to do, but that doesn't seem to be a very good idea. You're literally (programmatically) causing 444 clicks that don't really exist to happen. If one day you decide to track user clicks on those items, you'll have a problem.

What if you try to add a class to the common parent of those 444 leaflet-popup-close-button that force them, via CSS to collapse/close?

Something like that would be a better solution for what you're trying to do.

Btw, checking their docs it seems like these popups are all open on a new layer, so you probably just need to remove that layer and all of them will be gone.

From their docs:

Use Map#openPopup to open popups while making sure that only one popup is open at one time (recommended for usability), or use Map#addLayer to open as many as you want.

And checking further you have addLayer and removeLayer. Whatever you do, I'd suggest you avoid all those programmatically clicks.

2
votes

For recent versions of Leaflet:

The proper way to close a popup is to use the built-in .closePopup() method:

map.closePopup();

If you have multiple layers with different popups (like in the OP's case), then you could iterate over the layers and close the popup on each layer:

map.eachLayer(function (layer) {
  layer.closePopup();
});
1
votes

This is what i did to solve my problem:

var firstLayer = true;

 map.eachLayer(function (layer) {
    // do something with the layer
    if (firstLayer) {
        firstLayer = false;
    } else {
        map.removeLayer(layer);
    }
    //console.log(layer);
});

I have 3 layers, the first one is the main one which displays my map, that's why it mustn't be removed. I removed the second and the third one which are both layers with multiple popups on it.

Thanks @rafaelbiten who pointed me in the right direction (layers).