【问题标题】:Create a feature based on coordinates previously saved in localStorage OL3根据之前保存在 localStorage OL3 中的坐标创建要素
【发布时间】:2017-03-14 18:26:39
【问题描述】:

当用户单击一个按钮时,我正在创建一个功能,该按钮将创建一个功能并使用geolocation() 将他们的位置保存到localStorage()。如果用户然后刷新页面,或导航到不同的页面并且他们回来,我希望它重新绘制该功能。由于某种原因,这不起作用,我没有收到任何控制台错误。每当我将localStorage 版本添加到源代码时,它似乎都会中断。

这是我第一次在点击功能上绘制它的地方

var coords = geolocation.getPosition();
swal("Your location has been pinned! " + coords)
var parkedCar = new ol.Feature({
    geometry: new ol.geom.Point(coords)
})
localStorage.setItem("parkedCarCoords", coords);
parkedCar.setId("parkedCar");
parkedCar.setStyle(styleNS.styleFunction(styleConfig.parkedCarStyle));
geoLocationSource.addFeature(parkedCar);

这是我在页面加载时检查它并尝试绘制特征的地方

if (localStorage.getItem("parkedCarCoords")) {
        var parkedCar = new ol.Feature({
            geometry: new ol.geom.Point([localStorage.getItem("parkedCarCoords")])
        })
        parkedCar.setId("parkedCar");
        parkedCar.setStyle(styleNS.styleFunction(styleConfig.parkedCarStyle));
        geoLocationSource.addFeature(parkedCar);
    }

当我尝试执行此操作时,该功能根本不会从我的点击功能或我的 localStorage 中显示出来。

我尝试将 localStorage 版本添加到它自己的源中,但结果相同。如果我从 localStorage 版本中删除 geoLocationSource.addFeature(parkedCar); 行,则单击功能将起作用。可能还值得注意的是,我在同一层上有一个地理定位跟踪功能,当我尝试实现这个 localStorage 功能时它也没有显示出来。

【问题讨论】:

    标签: javascript jquery gis openlayers openlayers-3


    【解决方案1】:

    我认为当您尝试从 localStorage 检索坐标时会出错。当您在 localStorage 中设置和获取坐标时,它们将转换为字符串。您正在将此字符串传递给 Point,它需要一个数组作为输入。

    localStorage.setItem('coords', [1,1]);
    
    localStorage.getItem('coords');
    // Returns: "1,1" instead of [1,1]
    
    // To pass these coordinates to a Point, use the split function
    var coords = localStorage.getItem('coords').split(',');
    new ol.geom.Point(coords);
    

    【讨论】:

      【解决方案2】:

      localStorage 对象以字符串格式存储项目,因此当您执行 localStorage.setItem("parkedCarCoords", [1, 2]); 时,您存储的是字符串 1,2 而不是数组对象。

      同样,当您执行localStorage.getItem("parkedCarCoords"); 时,您会收到字符串1,2,因此[localStorage.getItem("parkedCarCoords")] 等于["1,2"]

      你需要将getItem的结果拆分成一个坐标数组:

      var parkedCar = new ol.Feature({
              geometry: new ol.geom.Point(localStorage.getItem("parkedCarCoords").split(','))
       })
      

      【讨论】:

        猜你喜欢
        • 2023-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-22
        • 2015-08-13
        相关资源
        最近更新 更多