在 localStorage 中保存 mapbox window 的边界,然后将它们加载到 refresh/reload
Saving bounds of mapbox window in localStorage and then loading them on refresh/reload
我正在为我的项目使用 mapbox-gl-js。
目前,它工作得很好,除了当我重新加载时,地图会回到我设置的初始边界。
我希望当页面刷新时,mapbox 回到页面重新加载的边界。
为此,我尝试将边界保存到 localStorage 中,但不知何故它不起作用。
我做了一个 if 条件,如果边界存在于本地存储中,则使用这些边界,否则从 mapbox 内置函数获取边界。
retrieveMapData() {
const savedBounds = localStorage.getItem('bounds');
if (savedBounds) {
return savedBounds;
} else {
this.bounds = this.getMap().getBounds();
}
this.createPolygon();
}
createPolygon() {
localStorage.setItem('bounds', this.bounds);
this
.mapDataManager
.getData(this.bounds)
.subscribe((data) => {
this.setSource('markerSource', this.prepareGeoJsonData(data));
});
}
我希望 mapbox 检查 localStorage 中是否存在边界,如果存在,则加载这些边界,如果不存在,则从内置函数加载边界。
目前,if 条件完全不起作用。
我遇到的解决方案是:
我们需要关注地图的中心而不是边界。
所以我简单地使用 getCenter() 获取地图的中心,并将其保存在 localStorage
现在,边界是自动计算和更新的。
这是工作代码:
this.mapInstance = new mapboxgl.Map({
container: 'map',
minZoom: 0,
maxZoom: 18,
center: this.getCenterOfMap(),
zoom: this.getZoomValueOfMap(),
style: this.style.streets
});
getCenterOfMap () {
try {
this.savedCenter = JSON.parse(localStorage.getItem('center'));
} catch (exception) {
console.log('Exception: ', exception);
}
if (this.savedCenter) {
return this.savedCenter;
} else {
return this.defaultCenter;
}
}
我正在为我的项目使用 mapbox-gl-js。 目前,它工作得很好,除了当我重新加载时,地图会回到我设置的初始边界。 我希望当页面刷新时,mapbox 回到页面重新加载的边界。
为此,我尝试将边界保存到 localStorage 中,但不知何故它不起作用。 我做了一个 if 条件,如果边界存在于本地存储中,则使用这些边界,否则从 mapbox 内置函数获取边界。
retrieveMapData() {
const savedBounds = localStorage.getItem('bounds');
if (savedBounds) {
return savedBounds;
} else {
this.bounds = this.getMap().getBounds();
}
this.createPolygon();
}
createPolygon() {
localStorage.setItem('bounds', this.bounds);
this
.mapDataManager
.getData(this.bounds)
.subscribe((data) => {
this.setSource('markerSource', this.prepareGeoJsonData(data));
});
}
我希望 mapbox 检查 localStorage 中是否存在边界,如果存在,则加载这些边界,如果不存在,则从内置函数加载边界。
目前,if 条件完全不起作用。
我遇到的解决方案是:
我们需要关注地图的中心而不是边界。
所以我简单地使用 getCenter() 获取地图的中心,并将其保存在 localStorage
现在,边界是自动计算和更新的。
这是工作代码:
this.mapInstance = new mapboxgl.Map({
container: 'map',
minZoom: 0,
maxZoom: 18,
center: this.getCenterOfMap(),
zoom: this.getZoomValueOfMap(),
style: this.style.streets
});
getCenterOfMap () {
try {
this.savedCenter = JSON.parse(localStorage.getItem('center'));
} catch (exception) {
console.log('Exception: ', exception);
}
if (this.savedCenter) {
return this.savedCenter;
} else {
return this.defaultCenter;
}
}