How to close all popups programmatically in mapbox gl?

后端 未结 3 1694
庸人自扰
庸人自扰 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 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.

提交回复
热议问题