3

https://jsfiddle.net/MaxHeadroom/s6h40xrn/

If you resize the map size, the zoom level should be adapted to always show the orange rectangle at maximum possible size.

But fitBounds seems to be broken after resizing the map. Same problem with map.getBoundsZoom().

To reproduce the buggy behaviour, start with a small map size - increase it and decrease it then. Check the console output too.

Or is there some a mistake in my source code?

3 Answers 3

5

The problem is that you're locking the minZoom and the map can't jump to the next zoom level out to keep the bounds within the view.

The solution is set minZoom one zoom step smaller temporarily so the map can resize if it needs to:

function map_onResize(e){    
    map.setMinZoom(map.getZoom()-1)
    map.fitBounds(bounds, true);
    map.setMinZoom(map.getZoom());
}
4

You should call map.invalidateSize() after you change the map size. Or maybe try to wait

var corner1 = L.latLng(50.012, 8.227);
var corner2 = L.latLng(50.074, 8.125);
var bounds  = L.latLngBounds(corner1, corner2);
var rectangle = L.rectangle(bounds, {color: "#ff7800", weight: 3}).addTo(map);
function map_onResize(e){
    map.invalidateSize();
    //setTimeout(function(){
      map.fitBounds(rectangle.getBounds(), true);
    //},800)    
} 
5
  • Have you checked the fiddle? Please look at line 20 there ....
    – Sysout
    Commented Oct 2, 2018 at 15:48
  • I've just added the sample code. It works for me
    – ranggalawe
    Commented Oct 2, 2018 at 15:50
  • Yep, the bbox rectangle limit didn't work as smooth as expected. But i would play with map.setZoom(map.getBoundsZoom(rectangle.getBounds())); or map.setMaxBounds(rectangle.getBounds()); to set the contraint to the rectangle
    – ranggalawe
    Commented Oct 2, 2018 at 16:33
  • 1
    I inserted your changes to the fiddle: jsfiddle.net/MaxHeadroom/s6h40xrn/44 Ranggalawe, your code is NOT working. no surprise - you added (logically) nothing to my code :(
    – Sysout
    Commented Oct 2, 2018 at 16:57
  • You saved my day, thank you. Commented Jan 13, 2020 at 8:49
0

Using this code also worked perfectly for me when replacing it in the given example: https://jsfiddle.net/MaxHeadroom/s6h40xrn/

function map_onResize(e){
    setTimeout(function(){
        const wantedZoom = map.getBoundsZoom(bounds, true);
        map.setMinZoom(wantedZoom-1);
        map.fitBounds(bounds, true);
    }, 500);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.