April 3, 2019

How to add an offset to Mapbox center

I am currently working on a project which displays a Mapbox map with an overlay on the top in the map. The map itself is centered to a specific marker and it draws a line from one marker to another. When loading the map, the overlay unfortunately covers up the line, which is an issue if the user cannot see a route or something important displayed underneath the overlay.

What you could do is to calculate an offset from the latitude and longitude that centers the map. But this is unnecessary complicated and Mapbox itself offers a method which solves that issue nicely. The method I am talking about is called "flyTo" and can be used liked this:

this.map.flyTo({
    center: [144.985258, -37.807426],
    offset: [300, 0],
    speed: 0.8,
})

Since I used Mapbox in combination with React.js and the "react-mapbox-gl" npm package I needed to call the flyTo method once the map is loaded. To solve this I used the "onStyleLoad" prop on the Map component itself.

<Map
    style="mapbox://styles/mapbox/streets-v9"
    zoom={[12]}
    onStyleLoad={map => {
        if (map.loaded) {
            map.flyTo(flyToOptions);
        }
    }}
/>

Once map.loaded returns true it will call the flyTo method and center the map with the offset you set in the options as argument.

>>> Check out my Udemy courses.