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?


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.fitBounds(bounds, true);
| improve this answer | |

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.fitBounds(rectangle.getBounds(), true);
| improve this answer | |
  • Have you checked the fiddle? Please look at line 20 there .... – Sysout Oct 2 '18 at 15:48
  • I've just added the sample code. It works for me – ranggalawe Oct 2 '18 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 Oct 2 '18 at 16:33
  • 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 Oct 2 '18 at 16:57
  • You saved my day, thank you. – Tugrul Emre Atalay Jan 13 at 8:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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