Mapbox GL JS: Change popup offset on zoom level

Viewed 1690

Depending on the current zoom level of my Mapbox map the marker icons have a different size. All my custom marker are in a div container and I change the class to change the size of them.

Now I have the problem that the offset of the popups (distance of the popup to the marker icon) is too big if the icons are smaller.

Is there a possibility to change the offset of the popups also with the zoom level?

2 Answers

In my case there was no css class being applied depending on the zoom level. What I did was to force a custom class from a listener on the zoom level. Something like:

this.map.on('zoom', () => {
    if (this.map.getZoom() > 8) {
        // zooming in, remove offset to position
        var popups: any = document.getElementsByClassName("mapboxgl-popup");
        for (let popup of popups) {
            if (popup.classList.contains("my-offset-class")) {
                popup.classList.remove("my-offset-class");
            }
        }
    } else {
        // zooming out, add left offset to position
        var popups: any = document.getElementsByClassName("mapboxgl-popup");
        for (let popup of popups) {
            if (!popup.classList.contains("my-offset-class")) {
                popup.classList.add("my-offset-class");
            }
        }
    }
});

Here mapboxgl-popup is the standard css class for popups (you may want to use any custom class you want providing you apply it on your popups), while my-offset-class is the css class for applying the offset.

Related