Raruto / leaflet-rotate

Leaflet plugin that allows to add rotation functionality to map tiles
GNU General Public License v3.0
81 stars 23 forks source link

getBoundsZoom behave differently depending on the zoom level you currently are. #25

Closed rphlo closed 1 year ago

rphlo commented 1 year ago

Here is illustration of issue.

https://jsfiddle.net/kjpe1ys5/1/

I believe the use of mapBoundsToContainerBounds in getBoundsZoom is the root cause of this issue.

rphlo commented 1 year ago

L.Map::mapBoundsToContainerBounds makes call to L.Map::latLngToContainerPoint which is rounding values is the problem.

Raruto commented 1 year ago

For those interested in learning more, I'll try to expand the concept explained by https://github.com/Raruto/leaflet-rotate/issues/25#issuecomment-1434397860

Offending code

var bounds = [[60.81123, 25.71632], [60.81028, 25.73166], [60.7997, 25.72892], [60.80061, 25.71362]];

// 1. draw a small rectangle on map
L.rectangle(bounds).addTo(map);

// 2. set a zoom level really far away from that bounds
map.setZoom(0, {animate: false});

// 3. trigger the bug
map.fitBounds(bounds, { animate: false });

// 4. run it once more to make it work properly
// map.fitBounds(bounds, { animate: false });

NB the { animate: false } parameter is optional, it's just for copy-pasting all above code into the browser console (otherwise you may not see the bug).

The actual final problem is due to the fact that when zoom = 0 the following calculation:

map.mapBoundsToContainerBounds(L.latLngBounds(bounds)).getSize();

returns an incorrect value: { x: 0, y: 0 }, which results in an infinite zoom level calculation (ref: L.Map::getScaleZoom) after the first map.fitbounds call:

...

map.setZoom(0, {animate: false});

map.fitBounds(bounds, { animate: false });
console.log(map.getZoom()); // zoom = 24 (ie. map maxZoom level == Infinity)

map.fitBounds(bounds, { animate: false });
console.log(map.getZoom()); // zoom = 13

Below the same portion of code that causes the above bug within L.Map::getBoundsZoom:

https://github.com/Raruto/leaflet-rotate/blob/16d7b3568df12a607ca2de298151636271e0e118/src/map/Map.js#L418-L436

👋 Raruto