Skip to content
Advertisement

MapBox GL JS marker offset

I’m using MapBox GL JS to create a map with a custom marker:

var marker = new mapboxgl.Marker(container)
    .setLngLat([
        datacenters[country][city].coordinates.lng,
        datacenters[country][city].coordinates.lat
    ])
    .addTo(map);

However, I seem to have some kind of offset problem with the marker. The thing is: when zoomed out a bit, the bottom of the marker is not really pointing to the exact location:

Marker when zoomed out a bit

When I’m zooming in a bit further it reaches its destination and it’s pointing to the exact spot.

Marker when zoomed in

I really love MapBox GL, but this particular problem is bugging me and I’d love to know how to solve it. When this is fixed my implementation is far more superior to the original mapping software I was using.

Advertisement

Answer

From Mapbox GL JS 0.22.0 you’re able to set an offset option to the marker. https://www.mapbox.com/mapbox-gl-js/api/#Marker

For example to offset the marker so that it’s anchor is the middle bottom (for your pin marker) you would use:

var marker = new mapboxgl.Marker(container, {
        offset: [-width / 2, -height]
    })
    .setLngLat([
        datacenters[country][city].coordinates.lng,
        datacenters[country][city].coordinates.lat
    ])
    .addTo(map);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement