根据先前保存在 localStorage OL3 中的坐标创建特征

Create a feature based on coordinates previously saved in localStorage OL3

我正在创建一个地图项,当用户单击将创建地图项并使用 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 功能时它也没有显示。

我认为当您尝试从 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);

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(','))
 })