【问题标题】:Saving bounds of mapbox window in localStorage and then loading them on refresh/reload在 localStorage 中保存 mapbox 窗口的边界,然后在刷新/重新加载时加载它们
【发布时间】:2019-04-16 15:26:47
【问题描述】:

我正在为我的项目使用 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 条件完全不起作用。

【问题讨论】:

  • 无法在 savedBounds 中工作为空?还是别的什么?
  • 实际上,问题是我得到了边界,但我需要将它们转换为坐标并将地图居中。如何将边界转换为坐标?
  • 尝试使用bounds.getCenter(),如果是边界或地图对象,则使用map.getCenter() 更好。
  • map.getBounds().toArray() ?
  • 或者甚至尝试 hash: true 作为地图选项

标签: angular typescript mapbox mapbox-gl-js bounds


【解决方案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;
    }
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2016-10-07
    • 2018-06-12
    • 2013-05-06
    • 2018-08-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多