How to close all popups programmatically in mapbox gl?

后端 未结 3 1700
庸人自扰
庸人自扰 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: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('
    Hello
    ').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');
    

提交回复
热议问题