问题
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 when the button is clicked.
What I have so far:
var testbtn = document.getElementById('test1');
var testbtn2 = document.getElementById('test2');
google.maps.event.addDomListener(testbtn, 'click', hide);
google.maps.event.addDomListener(testbtn2, 'click', show);
function hide() {
set_speed_camera(null);
localStorage.setItem("hide_speed_camera", "true");
}
function show() {
set_speed_camera(map);
localStorage.setItem("show_speed_camera", "true");
}
$(document).ready(function(e) {
if(JSON.parse(localStorage.getItem("show_speed_camera"))) {
set_speed_camera(map);
alert('testing..Show')
}
});
$(document).ready(function(e) {
if(JSON.parse(localStorage.getItem("hide_speed_camera"))) {
set_speed_camera(null);
alert('testing..Hide')
localStorage.removeItem('hide_speed_camera');
}
});
回答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);
function hide() {
set_speed_camera(null);
localStorage.setItem("hide_speed_camera", "true");
}
function show() {
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
.
回答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:
function hide() {
set_speed_camera(null);
localStorage.setItem("showing_speed_camera", "false");
}
function show() {
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);
}
来源:https://stackoverflow.com/questions/31351670/local-storage-for-google-map-markers