I created a function that on click places a marker on map, and save it to localstorage. Inside the marker popup, its displayed the marker position, and a delete button.
How I can make that delete button get actual marker position, compare to the ones stored in localstorage, and if find an equal value, delete it from local storage?
Using this:
for ( var i = 0, len = localStorage.length; i < len; ++i ) {
console.log( localStorage.getItem( localStorage.key( i ) ) );
}
I get the what's in localstorage, I noticed that the markers are saved with a "\", any way to improve this code?
["{\"lat\":1780,\"lng\":456}","{\"lat\":1280,\"lng\":904}","{\"lat\":1000,\"lng\":-132}","{\"lat\":216,\"lng\":300}"]
The code:
function onMapClick(e) {
var geojsonFeature = {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [e.latlng.lat, e.latlng.lng]
}
}
var marker;
L.geoJson(geojsonFeature, {
pointToLayer: function(feature, latlng){
marker = L.marker(e.latlng, {
title: "Resource Location",
alt: "Resource Location",
riseOnHover: true,
draggable: false,
icon: totem
}).bindPopup("<span>X: " + e.latlng.lng + ", Y: " + e.latlng.lat + "</span><br><a href='#' id='marker-delete-button'>Delete marker</a>");
marker.on("popupopen", onPopupOpen);
marker.on("dragend", function (ev) {
var chagedPos = ev.target.getLatLng();
this.bindPopup(chagedPos.toString()).openPopup();
});
// Begin store markers in local storage
storeMarker(e.latlng);
// End store markers in local storage
return marker;
}
}).addTo(map);
}
function onPopupOpen() {
var tempMarker = this;
$("#marker-delete-button:visible").click(function () {
map.removeLayer(tempMarker);
localStorage.removeItem("markers");
});
}
/// Load markers
function loadMarkers(){
var markers = localStorage.getItem("markers");
if(!markers) return;
markers = JSON.parse(markers);
markers.forEach(function(entry) {
latlng = JSON.parse(entry);
var geojsonFeature = {
"type": "Feature",
"properties": {},
"geometry": {
"type": "Point",
"coordinates": [latlng.lat, latlng.lng]
}
}
var marker;
L.geoJson(geojsonFeature, {
pointToLayer: function(feature){
marker = L.marker(latlng, {
title: "Resource Location",
alt: "Resource Location",
riseOnHover: true,
draggable: true,
icon: totem
}).bindPopup("<span>X: " + latlng.lng + ", Y: " + latlng.lat + "</span><br><a href='#' id='marker-delete-button'>Delete marker</a>");
marker.on("popupopen", onPopupOpen);
return marker;
}
}).addTo(map);
});
}
/// Store markers
function storeMarker(marker){
var markers = localStorage.getItem("markers");
if(!markers) {
markers = new Array();
console.log(marker);
markers.push(JSON.stringify(marker));
}
else
{
markers = JSON.parse(markers);
markers.push(JSON.stringify(marker));
}
console.log(JSON.stringify(markers));
localStorage.setItem('markers', JSON.stringify(markers));
}
map.on('click', onMapClick);
loadMarkers();