Search code examples
mapboxmapbox-gl

How to fit bounds and set max bounds at same time on window resize in MAPBOX?


To fit the map we use mapbox.fitBounds() and to set we do mapbox.setMaxBounds(), which avoid panning. This work's perfectly well on first load.

But on Window resize map get cropped and take the bounds reference from initially set maxbounds. I am trying to fit the map in viewport using setTimeout, so that map first fit on screen and then getting map bounds from mapbox.getBounds() set the value in mapbox.setMaxBounds(). But this is just an hack.

Is there any correct way to do so?

Please help... and thank you..


Solution

  • Hope you are all well...

    After many days of struggle, we are able to find the perfect solution, for my own question posted...

    Firstly,

    mapbox.fitBounds() is the method on passing given bounds as args, will fit the geometry(polygon etc..), making the center point in the middle. But the only thing it does not disallow panning.

    However, we can disallow panning using mapbox.setMaxBounds() which allow us to constrained to passed bounds.

    But on window resize, somehow mapbox Map change the bounds as per internal logic, which will no longer be the same as passed bounds initially...

    In order to fit the geometry on the viewport, at the same time disallow panning on window resize, we use Resize Observer to observe map's container, and in its callback, we just wrote, three lines

    1. Set map.setMaxBounds(null) //to null
    2. set fitbounds(bounds). //bounds of geometry that u have
    3. Get bounds from viewport using
       let bnds = mapbox.getBounds();
       and finally set in map.setMaxBounds(bnds);
    

    Note to pass the 3. point in requestAnimationFrame instead of setTimeout

    UPDATED Code

    MaxBounds and custom asymmetric padding in Mapbox GL

    Hope this will help...

    Thank you.