How can I save markers with Localstorage?

Hello,

I can set markers on the map but the next thing that I want to do is that the markers will stay on the map when I return to the page. I know that I can do it with Localstorage and I already tried it so as you can see in my code but it doesn’t work yet…

I hope someone has a solution for my question, thanks in advance.

index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Place marker with name</title>
</head>

<body>
        <div >
            <h1>Place marker with name</h1>
        </div>
    <div>
        <div>
            <div>
                <div>
                    <h2>Place and name marker</h2>
                </div>
                <div>
                    <form>
                        <div>
                            <div>
                                Place
                                <input id="place" type="text"><button id="search">search</button>
                            </div>
                            <div>
                                Name Marker<input id="namemarker" type="text">
                                Latitude<input id="latitude" type="text">
                                Longitude<input id="longitude" type="text">
                                <button id="add">add</button>
                                <button id="clear">clear</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <div>
                <div>
                    <div>
                        <h1>MAP</h1>
                    </div>
                </div>
                <div>
                    <div class="divmap"></div>
                </div>
            </div>
        </div>
    </div>

<script src="js/main.js"></script>

</body>

</html>

main.js

var posOptions =     { enableHighAccuracy: false,
    maximumAge: 0,
    timeout: 5000
};

/**  * Get the current location of the user  */
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showLocation, handleError, posOptions);
    } else {
        console.log ('Not supported');
    }
}

/**  * Show current location coords of the user  *
 *  @param position object with position info  */
function showLocation(position) {
    console.log(position.coords.latitude, position.coords.longitude );
}

function handleError(error) {
    console.log(error.code, error.message );
}



getLocation();

var markers = [];
var map;
var API_KEY = "MY_KEY";
var mapScript = document.createElement('script');
mapScript.setAttribute('src', 'https://maps.googleapis.com/maps/api/js?key='+API_KEY+'&callback=initMap' );
mapScript.setAttribute('async', '' );
mapScript.setAttribute('defer', '' );
document.querySelector('body').appendChild(mapScript);
function initMap() {
    navigator.geolocation.getCurrentPosition(showMap, handleError);
}

var divMap = document.querySelector(".divmap");
function showMap(pos) {
    divMap.style.width = '500px';
    divMap.style.height = '500px';
    var target = {
        lat: pos.coords.latitude,
        lng: pos.coords.longitude,
    };

    map = new google.maps.Map(divMap, {
        center:target,
        zoom: 16
    });

    makeMarker(target, 'Ik' );


}

var search = document.querySelector('#search');

search.addEventListener("click", function (ev) {
    ev.preventDefault();
    showPlace();
},false);

var add = document.querySelector('#add');

add.addEventListener("click", function (ev) {
    ev.preventDefault();
    savePlace();
}, false);

function showPlace() {
    var loc = document.querySelector('#place');

    console.log(loc.value);

    var reqUrl = "https://maps.googleapis.com/maps/api/geocode/json?address="+loc.value+"&key="+API_KEY;

    fetch(reqUrl)
        .then(function(response) {
            return response.json();
        })
        .then(function (locJson) {
            console.log(locJson);
            var pos = locJson.results[0].geometry.location;


            var long = locJson.results[0].geometry.location.lng;
            var longfield = document.querySelector('#longitude');
            longfield.focus();
            longfield.value = long;

            map.panTo(pos);

            var lat = locJson.results[0].geometry.location.lat;
            var latfield = document.querySelector('#latitude');
            latfield.focus();
            latfield.value = lat;

        });

}

function makeMarker(pos, namemarker){
    var marker = new google.maps.Marker({
        position: pos,
        map:map,
        title:namemarker,
    });
    markers.push(marker);
}

function savePlace() {
    var namemarker = document.querySelector('#namemarker').value;
    var latfield = Number(document.querySelector('#latitude').value);


    var longfield = Number(document.querySelector('#longitude').value);

    console.log(latfield, longfield);
    var pos = {
        lat: latfield,
        lng: longfield,
    };


    makeMarker(pos, namemarker);
    localStorage.setItem('MarkersList', JSON.stringify(markers));

}

var clear = document.querySelector('#clear');
clear.addEventListener("click", function (ev) {
    ev.preventDefault();
    clearMap();
}, false);

function clearMap() {
    markers = [];
    console.log(markers);
    localStorage.clear();
}



I don’t see anywhere in your code where you are retrieving anything from localStorage.

I tried this but it didn’t work…

var posOptions =     { enableHighAccuracy: false,
    maximumAge: 0,
    timeout: 5000
};

/**  * Get the current location of the user  */
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showLocation, handleError, posOptions);
    } else {
        console.log ('Not supported');
    }
}

/**  * Show current location coords of the user  *
 *  @param position object with position info  */
function showLocation(position) {
    console.log(position.coords.latitude, position.coords.longitude );
}

function handleError(error) {
    console.log(error.code, error.message );
}



getLocation();

var markers = [];
var map;
var API_KEY = "AIzaSyBHlzEXk1cGO65POSXz_AYW2DDmKuF6Fv4";
var mapScript = document.createElement('script');
mapScript.setAttribute('src', 'https://maps.googleapis.com/maps/api/js?key='+API_KEY+'&callback=initMap' );
mapScript.setAttribute('async', '' );
mapScript.setAttribute('defer', '' );
document.querySelector('body').appendChild(mapScript);
function initMap() {
    navigator.geolocation.getCurrentPosition(showMap, handleError);
}

var divMap = document.querySelector(".divmap");
function showMap(pos) {
    divMap.style.width = '500px';
    divMap.style.height = '500px';
    var target = {
        lat: pos.coords.latitude,
        lng: pos.coords.longitude,
    };

    map = new google.maps.Map(divMap, {
        center:target,
        zoom: 16
    });

    makeMarker(target, 'Ik' );


}

var search = document.querySelector('#search');

search.addEventListener("click", function (ev) {
    ev.preventDefault();
    showPlace();
},false);

var add = document.querySelector('#add');

add.addEventListener("click", function (ev) {
    ev.preventDefault();
    savePlace();
}, false);

function showPlace() {
    var loc = document.querySelector('#place');

    console.log(loc.value);

    var reqUrl = "https://maps.googleapis.com/maps/api/geocode/json?address="+loc.value+"&key="+API_KEY;

    fetch(reqUrl)
        .then(function(response) {
            return response.json();
        })
        .then(function (locJson) {
            console.log(locJson);
            var pos = locJson.results[0].geometry.location;


            var long = locJson.results[0].geometry.location.lng;
            var longfield = document.querySelector('#longitude');
            longfield.focus();
            longfield.value = long;

            map.panTo(pos);

            var lat = locJson.results[0].geometry.location.lat;
            var latfield = document.querySelector('#latitude');
            latfield.focus();
            latfield.value = lat;

        });

}

function makeMarker(pos, namemarker){
    var marker = new google.maps.Marker({
        position: pos,
        map:map,
        title:namemarker,
    });
    markers.push(marker);
}

function savePlace() {
    var namemarker = document.querySelector('#namemarker').value;
    var latfield = Number(document.querySelector('#latitude').value);


    var longfield = Number(document.querySelector('#longitude').value);

    console.log(latfield, longfield);
    var pos = {
        lat: latfield,
        lng: longfield,
    };


    makeMarker(pos, namemarker);
    localStorage.setItem('MarkersList', JSON.stringify(markers));

}

var clear = document.querySelector('#clear');
clear.addEventListener("click", function (ev) {
    ev.preventDefault();
    clearMap();
}, false);

function clearMap() {
    markers = [];
    console.log(markers);
    localStorage.clear();
}

function getSavedMarkers(){
    var savedMarkers = JSON.parse(localStorage.getItem("MarkersList"));
    if(savedMarkers.length > 0){
        savedMarkers.forEach(function (marker) {
            var markerName = marker.title;
            map = marker.map;
            var pos = marker.position;

            showMap(pos, markerName);
        });
    }
}

getSavedMarkers();