Dev
Dev

Reputation: 23

Mapbox fitBounds does not accept coordinates - stays in Kenya

I just started with MapBox and have this code (simply copied the code from this sample https://docs.mapbox.com/mapbox-gl-js/example/fitbounds/ and replaced the coords):

document.getElementById('fit').addEventListener('click', function () {
map.fitBounds([
[43.965830, -9.839989],
[36.150694, 5.506686]
]);

This should give the map of Spain, alas I still end up in Kenya

Where might the error be?

Thanks

Upvotes: 1

Views: 592

Answers (2)

hoogw
hoogw

Reputation: 5525

fitBounds accepts a southwest, northeast bounding box and not an array of coordinates.

I create a LngLatBounds object and then loop through the coordinates of my polygon and extends the bounds.

Please look this example:

Fit to the bounds of a LineString

https://docs.mapbox.com/mapbox-gl-js/example/zoomto-linestring/

or there is github issue about this:

map.fitBounds() does not fit the entire bounds #11617

https://github.com/mapbox/mapbox-gl-js/issues/11617

Here is my working code sample

enter image description here

Upvotes: 0

jscastro
jscastro

Reputation: 3780

Your coordinates are reversed... try this and it will smoothly jump to Spain

    document.getElementById('fit').addEventListener('click', function () {
        map.fitBounds([
            [-9.839989, 43.965830],
            [5.506686, 36.150694]
        ]);
    });

enter image description here

Upvotes: 0

Related Questions