谷歌地图标记的本地存储

时间:2015-07-10 23:12:27

标签: javascript google-maps google-maps-api-3 local-storage

如何在我的代码中加入localStorage?我在谷歌地图上有一个隐藏和显示标记数组的显示和隐藏按钮。单击按钮时,我需要将值存储在localStorage中。

到目前为止我所拥有的:

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');
    } 
});

2 个答案:

答案 0 :(得分:0)

您有一个明显的问题,即您使用localStorage.getItem来获取 stringified 布尔值。而是将JSON.parse投射到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

因此,除非您使用JSON.parse,否则getItem的结果将始终为true

答案 1 :(得分:0)

localStorage将所有内容存储为字符串。您需要检查当前设置的字符串形式。

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

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

此外,您有两个字符串布尔控制相同的功能。也许不是同时将show_speed_camerahide_speed_camera存储在localStorage中,只需要showing_speed_camera,就像这样:

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); 
}