Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapbox.js: set map bounds on an area on both side of the date-line

In Mapbox, the fitBounds method doesn't seem to play nicely with points that are on both sides of the Atlantic (where the coords jump from 359 to 0).

How is it possible fit the bounds of Alaska or a flight from HK to SF. It might be possible to code a workaround making use of a center point and a custom zoom-level but it feel like a overengineered workaround around a poor handling of the bounds.

If firBounds is no help, is there another method like that would achieve similar results?

Example of fitBounds around Alaska, since Alaska crosses the antimeridian:

map.fitBounds([[172.461667,71.365162],[-129.979511,51.214183]])
like image 479
Félix Ménard Avatar asked Dec 02 '25 21:12

Félix Ménard


1 Answers

Those cases are always a bit of a pain. What may help is wrapping your bounding box coordinates using:

https://www.mapbox.com/mapbox-gl-js/api/#lnglat#wrap

Another solution might be to convert the bounds to a center & zoom value using:

https://github.com/mapbox/geo-viewport

const {width, height} = map.getCanvas().getBoundingClientRect();
const viewport = geoViewport(
      [minX, minY, maxX, maxY],  // the bounding box (west, south, east north)
      [width, height], // map dimensions in pixel
      0,  // minzoom
      22, // maxzoom
      512 // tilesize for mapbox-gl-js
    );
map.setCenter(viewport.center);
map.setZoom(viewport.zoom)
like image 188
Scarysize Avatar answered Dec 05 '25 09:12

Scarysize



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!