我必须保存 map 的缩放级别。在 map 的缩放结束函数中,我将其保存在本地存储中,并且在再次渲染组件时,我尝试检查是否保留了任何缩放值。基于它,我尝试渲染 map 。一切都工作正常,但我还需要保存位置,所以我尝试获取边界并执行与缩放级别相同的操作。它不起作用,如果有任何值,我尝试应用 fitBounds在本地存储中。请帮我解决这个问题。
initializeMap = () => {
const { user } = this.props;
const zoomLevel = localStorage.getItem('itemsZoom');
let boundCoordinates = {};
boundCoordinates = JSON.parse(localStorage.getItem('itemsBounds'));
if (zoomLevel !== null && Object.keys(boundCoordinates).length > 0) {
this.map.fitbounds(boundCoordinates);
}
this.map.fitbounds(boundCoordinates);
this.map = L.map('map', {
center: [38.778, -73.554]
zoom: zoomLevel !== null ? zoomLevel : 18
});
L.gridLayer.googleMutant({ type: 'satellite', maxZoom: 20 }).addTo(this.map);
this.map.on(L.Draw.Event.CREATED, (e) => {
this.onMarkerCreated(e);
});
this.map.on('draw:editmove', (e) => {
this.onMarkerEdited(e);
});
this.map.on('zoomend', (e) => {
const zoom = this.map.getZoom();
localStorage.setItem('itemsZoom', zoom);
const bounds = this.map.getBounds();
localStorage.setItem('itemsBounds', JSON.stringify(bounds));
});
}
最佳答案
使用它来保存边界localStorage.setItem('itemsBounds',this.map.getBounds().toBBoxString()))
然后当你读出调用时:
[west, south, east, north] = localStorage.getItem('itemsBounds').split(',').map(parseFloat)
var bounds = new L.LatLngBounds(new L.LatLng(south, west), new L.LatLng(north, east))
this.map.fitBounds(bounds);
PS:fitBounds
与“B”
关于javascript - 如何渲染带有保存在传单中的 Zoomend 函数上的边界的 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60526719/