Skip to content Skip to sidebar Skip to footer

Local Storage For Google Map Markers

How do I incorporate localStorage in my code? I have a show and hide button on my google map that will Hide and Show a marker array. I need to store the values in localStorage whe

Solution 1:

You have one obvious issue, which is that you are using localStorage.getItem to get the stringified boolean. Instead, cast a JSON.parse to your getItem:

var testbtn = document.getElementById('test1');
var testbtn2 = document.getElementById('test2');
google.maps.event.addDomListener(testbtn, 'click', hide);
google.maps.event.addDomListener(testbtn2, 'click', show); 


functionhide() {    
    set_speed_camera(null);
    localStorage.setItem("hide_speed_camera", "true");
}

functionshow() {
    set_speed_camera(map);
    localStorage.setItem("show_speed_camera", "true");
}
if(JSON.parse(localStorage.getItem("show_speed_camera"))) {    
    set_speed_camera(map);
}
if(JSON.parse(localStorage.getItem("hide_speed_camera"))) {
    set_speed_camera(null);
} 

> Boolean("true")
true
> Boolean("false")
true

Thus, unless you use a JSON.parse, the result of the getItem will always be true.

Solution 2:

localStorage stores everything as strings. You need to check what the current setting is in its string form.

if(localStorage.getItem("show_speed_camera") === "true") {
    set_speed_camera(map);     
}

if(localStorage.getItem("hide_speed_camera") === "true") { 
    set_speed_camera(null); 
} 

Also, you have two stringified booleans controlling the same functionality. Perhaps instead of having both a show_speed_camera and a hide_speed_camera stored in localStorage, just have a showing_speed_camera, like this:

functionhide() {
       set_speed_camera(null);
       localStorage.setItem("showing_speed_camera", "false");      
}

functionshow() {
      set_speed_camera(map);
      localStorage.setItem("showing_speed_camera", "true");
}


if(localStorage.getItem("showing_speed_camera") === "true") {
    set_speed_camera(map);     
}

if(localStorage.getItem("hide_speed_camera") === "false") { 
    set_speed_camera(null); 
} 

Post a Comment for "Local Storage For Google Map Markers"