Search code examples
javascriptlocal-storageleafletmarkers

How to remove specific item from local Storage and layergroup on leaflet?


I am trying to save on localstorage the markers that I create on click in leaflet and delete them using a button. The problem is that I don't know how to delete just one marker at time and remove them from the main layer without affecting the others.

I want to add a unique id to each marker created (that's why the "Marker #") and later on delete see if the current marker's id or location (lat,lng) match the one stored on localstorage, then delete it from the localstorage and remove it from the main layer.

Anyone could help me solve this? This is giving me headaches!

I am using this function to add them on the map and in localstorage:

initUserLayerGroup();

map.on('click', onMapClick);

var groupUser;

function initUserLayerGroup() {
    if (localStorage.userMarkers !== undefined) {
        var storageMarkers = [];
        var markersUser = [];

        storageMarkers = JSON.parse(localStorage.userMarkers);

        for (var i = 0; i < storageMarkers.length; i++) {
            var x = storageMarkers[i].coords.x;
            var y = storageMarkers[i].coords.y;
            var name = storageMarkers[i].name;

            var marker = L.marker([y, x]).bindPopup(name + "<br><a href='#' class='delete'>Delete</a>");

            marker.on("popupopen", onPopupOpen);

            markersUser.push(marker);
        }

        groupUser = L.layerGroup(markersUser);

        map.addLayer(groupUser);
    }
}

function onMapClick(e) {
    var storageMarkers = [];
    var markersUser = [];

    if (localStorage.userMarkers !== undefined) {
        storageMarkers = JSON.parse(localStorage.userMarkers);
    }

    storageMarkers.push({
        "coords": {
            "x": e.latlng.lng,
            "y": e.latlng.lat
        },
        "name": "Marker #"
    });

    var x = storageMarkers[storageMarkers.length -1].coords.x;
    var y = storageMarkers[storageMarkers.length -1].coords.y;
    var name = storageMarkers[storageMarkers.length -1].name;

    var marker = L.marker([y, x]).bindPopup(name + "<br>X: "+ x +", Y: "+ y +"<br><a href='#' class='delete'>Delete</a>");

    marker.on("popupopen", onPopupOpen);

    markersUser.push(marker);

    groupUser = L.layerGroup(markersUser);

    map.addLayer(groupUser);

    localStorage.userMarkers = JSON.stringify(storageMarkers);
}

function onPopupOpen() {
    var tempMarker = this.getLatLng();

    $('.delete').click(function() {
        localStorage.removeItem('userMarkers');
        map.removeLayer(groupUser);
    });
}

You can see it working here:

http://plnkr.co/edit/vYDExBBqy9zCGBRZJ944?p=preview


Solution

  • One way is to iterate over the saved array of coordinates in localStorage when the marker is clicked and compare them with the coordinates of the clicked marker. Once they are the same, delete this item from localSotrage and update it.

    function onPopupOpen() {
      var _this = this;
      var clickedMarkerCoords = this.getLatLng();
    
      $('.delete').click(function() {
        storageMarkers = JSON.parse(localStorage.userMarkers);
        for(i = storageMarkers.length; i > 0; i--) {
          if (typeof storageMarkers[i] != 'undefined' && 
            (clickedMarkerCoords.lat == storageMarkers[i].coords.y &&
            clickedMarkerCoords.lng == storageMarkers[i].coords.x)
          ) {
            storageMarkers.splice(i, 1);
            localStorage.userMarkers = JSON.stringify(storageMarkers);
          }
        }   
        map.removeLayer(_this);
      });
    }
    

    Here is the plunker: http://plnkr.co/edit/1xVZjKC1184dfuOlGqVX?p=preview