How to close all popups programmatically in mapbox gl?

后端 未结 3 1712
庸人自扰
庸人自扰 2021-02-19 08:39

So, I know that we have Marker.togglePopup() in Mapbox GL Api. But Can we close all popups programmatically ?

相关标签:
3条回答
  • 2021-02-19 08:50

    Here is an example: https://jsfiddle.net/kmandov/eozdazdr/
    Click the buttons at the top right to open/close the popup.

    Given you have a popup and a marker:

    var popup = new mapboxgl.Popup({offset:[0, -30]})
        .setText('Construction on the Washington Monument began in 1848.');
    
    new mapboxgl.Marker(el, {offset:[-25, -25]})
        .setLngLat(monument)
        .setPopup(popup)
        .addTo(map);
    

    You can close the popup by calling:

    popup.remove();
    

    or you can open it by calling:

    popup.addTo(map);
    

    As you can see in the Marker source, togglePopup uses these two methods internally:

    togglePopup() {
        var popup = this._popup;
    
        if (!popup) return;
        else if (popup.isOpen()) popup.remove();
        else popup.addTo(this._map);
    }
    
    0 讨论(0)
  • 2021-02-19 08:57

    The accepted answer didn't apply to my use case (I wasn't using a Marker). I was able to come up with a different solution by utilizing the mapbox's built-in event workflow. Hopefully this helps someone else.

    Mapbox allows you to listen to events on the map (and manually trigger them). The documentation doesn't mention it, but you can use custom events.

    Given you have a popup:

    // Create popup and add it to the map
    const popup = new mapboxgl.Popup({ offset: 37, anchor: 'bottom' }).setDOMContent('<h5>Hello</h5>').setLngLat(feature.geometry.coordinates).addTo(map);
    
    // Add a custom event listener to the map
    map.on('closeAllPopups', () => {
      popup.remove();
    });
    

    When you want to close all popups, fire the event:

    map.fire('closeAllPopups');
    
    0 讨论(0)
  • 2021-02-19 09:09

    Mapbox automatically uses the class .mapboxgl-popup for the popup. You can also add additional classes with options.className.

    So, if you have jQuery available, just do:

    $('.mapboxgl-popup').remove();
    

    Or plain javascript:

    const popup = document.getElementsByClassName('mapboxgl-popup');
    if ( popup.length ) {
        popup[0].remove();
    }
    

    I'm pretty sure you can assume there's only ever one popup open. The default behavior seems to be that if one is open and a second item is clicked, the first popup is removed from the DOM completely when the second one opens. If your application allows multiple open popups somehow, you will need to loop through and remove each with plain js, instead of using the first item only.

    0 讨论(0)
提交回复
热议问题