我有一个位置对象的数组列表,我正在使用其中一些来构建完整的地址,然后对其进行地理编码。一旦我收到 OK 状态,我就会在地图上放置一个标记。这一切都很好。但是,现在我还想在每个标记上放置一个信息窗口,其中包含数组列表中的另一个属性 LocationName。
代码在这里:
function placeMarkers(myObjList){
var geocoder = new google.maps.Geocoder();
for(var i=0; i<myObjList.length; i++){
var fullAddress = myObjList[i].Address + ", " + myObjList[i].City + ", " + myObjList[i].State + ", " + myObjList[i].Zip;
/* The variable I would like to have access to in the geocode call */
var locationName = myObjList[i].LocationName;
geocoder.geocode( { 'address': fullAddress}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert(locationName);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
clickable: true
});
markers.push(marker);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
当我得到状态 OK 时,警报只是查看 locationName 是什么。但在测试中它总是相同的值。一旦我可以调整它以每次反映正确的值,然后我就可以排列代码以将信息窗口放置在标记上。
任何帮助将不胜感激!
最简单的事情可能是在循环中创建一个本地范围块,以便 locationName 实际上引用一个不同的每次添加委托/匿名函数来执行地理编码时的变量。将 var 放入循环中不会创建该变量的新实例,var 声明本质上会移动到封闭范围块的顶部。
for(var i=0; i<myObjList.length; i++){
var fullAddress = myObjList[i].Address + ", " + myObjList[i].City + ", " + myObjList[i].State + ", " + myObjList[i].Zip;
//begin scope block
(function(){
var locationName = myObjList[i].LocationName;
var yourObject = myObjList[i];
//etc.
geocoder.geocode( ...);
//end scope block
})();
}
Edit:
或者,如果您使用某些框架/允许您传递匿名函数来为数组中的每个项目执行代码,那么您会自动处理这种范围问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)