我在网页上有Google Maps Javascript API v3,并且正在使用地理编码库: https://developers.google.com/maps/documentation/javascript/geocoding
代码
在我的google.maps.Geocoder.geocode
回调函数中,我将lat,lng作为JSON保存到Chrome浏览器的window.localStorage
中,如下所示:
if (localStorage.getItem('geocode:'+job.url) === null) {
geocoder.geocode({'address': job.address}, function(results, status) {
var json = JSON.stringify({
address: job.address,
lat: results[0].geometry.location.lat(),
lng: results[0].geometry.location.lng()
});
console.log('Set key:"geocode:'+job.url+'", value: '+json);
localStorage.setItem('geocode:'+job.url, json);
console.log('Get key:"geocode:'+job.url+'", value: '+localStorage.getItem('geocode:'+job.url));
});
}
问题是我的关键是在回调函数之外设置为null。 运行上述代码并打印两条日志消息后,在控制台中键入此消息会显示问题:
> localStorage.length;
1
> localStorage.key(0);
"geocode:123 street San Francisco CA USA"
> localStorage.getItem("geocode:123 street San Francisco CA USA");
null
将localStorage密钥前缀更改为'blah:'可解决问题!
这是否意味着Google Maps Javascript API v3地理编码库会在回调函数返回后使用前缀“geocode:”覆盖localStorage键?
额外背景信息:
我在Chrome扩展程序网址的页面上包含此脚本代码,如:
<script src="chrome:///blah" type="text/javascript"></script>
从google.maps.Geocoder.geocode
处理程序调用对window.setTimeout
和回调函数的调用。