Search code examples
javascriptjquerygisopenlayersopenlayers-3

Create a feature based on coordinates previously saved in localStorage OL3


I am creating a feature when a user clicks a button that will create a feature and save their location into localStorage() using geolocation(). If the user then refreshes the page, or navigates to a different page and they come back, I want it to re-draw that feature. For some reason this does not work, I am not getting any console errors. It seems to break whenever I add the localStorage version to the source.

Here is where I draw it the first time on my click function

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);

And here is where I am checking for it on page load and trying to draw the feature

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);
    }

When I try and do this, the feature won't show up at all, from either my click function or my localStorage.

I tried to add the localStorage version to it's own source but that yielded the same result. The click function will work if I get rid of the geoLocationSource.addFeature(parkedCar); line from the localStorage version. It may also be worth noting that I have a geolocation tracking feature on the same layer, and it does not show up either when I try implementing this localStorage feature.


Solution

  • I think it goes wrong when you try to retrieve the coordinates from the localStorage. When you set and get the coordinates in localStorage, they are converted to a string. You are passing this string to Point, which expects an Array as input.

    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);