英文:
Leaflet.js Image overlay incorrectly positioned with `fitBounds()` until reflow/window resize
问题
以下是您要翻译的内容:
What I Did
用于生成地图的相关代码行:
let map = L.map('floorplan', { crs: L.CRS.Simple });
const imageUrl = floorplanUrl;
const imageBounds = [[0, 0], [1000, 1000]];
L.imageOverlay(imageUrl, imageBounds).addTo(map);
map.fitBounds(imageBounds);
Expected:
整个楼层平面图像显示在屏幕上,并填充地图区域。
Actual:
初始时,大部分楼层平面图像出现在屏幕外,但如果调整浏览器窗口大小(可能触发了回流),则会弹到预期位置。 (在Firefox和Chrome中都尝试过)。
初始显示在屏幕外的图像叠加层:
调整浏览器窗口大小后的图像叠加层:
我可以通过手动在窗口对象上分派调整大小事件来解决此问题:
const event = new Event('resize');
window.dispatchEvent(event);
但我怀疑我做错了什么,可能是对坐标系统的误解,或者页面上的某些其他CSS干扰。
我注意到第一个状态和第二个状态之间的区别在于第二个状态将leaflet-pane
和leaflet-map-pane
类的DIV添加了一个3D CSS变换:
transform: translate3d(530px, 248px, 0px);
我做错了什么?
英文:
I've added an image overlay to a non-geographical map using Leaflet.js and CRS.Simple for positioning. When I call map.fitToBounds(bounds)
the image overlay is initially displayed mostly off screen, but if the browser window is resized (presumably triggering a reflow) it pops into the expected position.
What I Did
The relevant lines of code used to generate the map:
let map = L.map('floorplan', { crs: L.CRS.Simple });
const imageUrl = floorplanUrl;
const imageBounds = [[0, 0], [1000, 1000]];
L.imageOverlay(imageUrl, imageBounds).addTo(map);
map.fitBounds(imageBounds);
Expected:
The whole floorplan image is displayed on the screen and fills the map area.
Actual:
Most of the floorplan image initially appears off screen, but moves into the expected position if the browser window is resized. (Tried in both Firefox and Chrome).
Image overlay displayed off screen:
Image overlay after resizing browser window:
I can work around this by manually dispatching a resize event on the window object:
const event = new Event('resize');
window.dispatchEvent(event);
But I suspect I'm doing something wrong, either misunderstanding the coordinate system, or maybe there's some interference with some other CSS on the page.
I've noticed that the difference between the first state and the second state is that in the second state a 3D CSS transform is added to the div with classes leaflet-pane
and leaflet-map-pane
:
transform: translate3d(530px, 248px, 0px);
What am I doing wrong?
答案1
得分: 1
感谢 @svrbst 和 @IvanSanchez。
地图的大小在内容完全加载之前已经设置好了。
以下是来自 stackoverflow.com/a/20402399/4768502 的一个更为独立的解决方法:
map.whenReady(() => {
setTimeout(() => {
map.invalidateSize();
}, 0);
});
这有点像是一种小技巧,但不幸的是,等待 DOMContentLoaded
或 load
事件似乎不起作用。
英文:
Thanks to @svrbst and @IvanSanchez.
The size of the map was being set before content had fully loaded.
A more isolated workaround from stackoverflow.com/a/20402399/4768502 :
map.whenReady(() => {
setTimeout(() => {
map.invalidateSize();
}, 0);
});
This is a bit of a hack but unfortunately waiting for DOMContentLoaded
or load
events does not seem to work.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论