Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close all popups programmatically in mapbox gl?

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

like image 404
Yahor Vaziyanau Avatar asked Nov 29 '16 06:11

Yahor Vaziyanau


People also ask

What does Mapbox GL stand for?

Mapbox GL maps render at a high frame rate. The abbreviation "GL" comes from OpenGL, the industry-standard Open Graphics Library. Mapbox GL allows you to use custom styles designed in Mapbox Studio.

Does Mapbox use WebGL?

Mapbox Studio is supported in browsers that support WebGL, a method of generating dynamic 3D graphics using JavaScript, accelerated through hardware. Mapbox Studio is compatible with all modern browsers, specifically: Safari 9 and above. Chrome latest.

Does Mapbox use JavaScript?

Mapbox GL JS is a JavaScript library for vector maps on the Web. Its performance, real-time styling, and interactivity features set the bar for anyone building fast, immersive maps on the web.


2 Answers

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);
}
like image 84
kmandov Avatar answered Oct 01 '22 07:10

kmandov


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');
like image 45
Dan Sterrett Avatar answered Oct 01 '22 07:10

Dan Sterrett