在localStorage中保存mapbox窗口的边界,然后在刷新/重新加载时加载它们

问题描述 投票:-1回答:1

我在我的项目中使用mapbox-gl-js。目前,除了当我重新加载时,地图会回到我设置的初始边界,它的工作正常。我希望当页面刷新时,mapbox会返回到重新加载页面的边界。

为此,我尝试将边界保存到localStorage,但不知何故它不起作用。我已经创建了一个if条件,如果bounds存在于localstorage中,请使用这些边界,否则从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条件完全不起作用。

angular typescript mapbox mapbox-gl-js bounds
1个回答
1
投票

我遇到的解决方案是:

我们需要关注地图的中心而不是边界。

所以我只是使用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;
    }
  }
© www.soinside.com 2019 - 2024. All rights reserved.