highliner
highliner

Reputation: 107

Mapbox GL JS: Change popup offset on zoom level

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?

Upvotes: 4

Views: 2562

Answers (2)

mdt
mdt

Reputation: 186

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.

Upvotes: 0

highliner
highliner

Reputation: 107

Sometimes the solution is easier than expected.. The Mapbox popups already have a class depending of the popup position to the marker (e.g. bottom right). Together with a zoom class I use additionally I can easily change the offset values with CSS. Here an example.

.zoom-4 > .mapboxgl-popup.mapboxgl-popup-anchor-bottom,
.zoom-4 > .mapboxgl-popup.mapboxgl-popup-anchor-bottom-left,
.zoom-4 > .mapboxgl-popup.mapboxgl-popup-anchor-bottom-right
{
    top: 10px;
}
.zoom-4 > .mapboxgl-popup.mapboxgl-popup-anchor-left {
    top: 6px;
    left: -4px;
}
.zoom-4 > .mapboxgl-popup.mapboxgl-popup-anchor-right {
    top: 6px;
    left: 2px;
}

Upvotes: 0

Related Questions