I have been banging my head against the desk for the last few hours.
I am trying to get Mapbox to zoom in on load to the bounding area of all my markers.
However, this is the error I am getting for the code below.
This error comes after the console log image below, so the lat lng coordinates are definitely there.
Uncaught Error: Invalid LngLat object: (NaN, NaN)
const onLoad = () => {
let points = [];
props.cats.forEach(cat => (
points.push([ cat.lat, cat.lng ])
));
points.length > 0 && ref.current.getMap().fitBounds(points, {
padding: { top: 50, bottom: 50, left: 50, right: 50 },
easing(t) {
return t * (2 - t);
},
});
};
If you have more than a pair of coordinates, you should first reduce the array with coordinates.reduce
, and then define the bounds through new mapboxgl.LngLatBounds
. After that you can fly with map.fitBounds
to the bounds, defining your favorite padding and easing function as you did in your code.
var coordinates = points;
var bounds = coordinates.reduce(function(bounds, coord) {
return bounds.extend(coord);
}, new mapboxgl.LngLatBounds(coordinates[0], coordinates[0]));
map.fitBounds(bounds, {
padding: { top: 50, bottom: 50, left: 50, right: 50 },
easing(t) {
return t * (2 - t);
}
});
I have prepared this fiddle with the solution how to fit bounds to a list of coords with an array of 3 coords, but you can apply easily to yours.