How to close all popups programmatically in mapbox gl?

后端 未结 3 1711
庸人自扰
庸人自扰 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);
    }
    

提交回复
热议问题