How to close all popups?

前端 未结 3 1988
广开言路
广开言路 2021-01-14 06:27

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

I tried this:

$(\".leaflet-popup-close-button\").each(function (index) {
    $         


        
相关标签:
3条回答
  • 2021-01-14 06:46

    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).

    0 讨论(0)
  • 2021-01-14 07:00

    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.

    0 讨论(0)
  • 2021-01-14 07:00

    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();
    });
    
    0 讨论(0)
提交回复
热议问题