GMaps实现JS地理code:使用/传递变量异步地理code函数? [英] GMaps JS Geocode: Using/Passing Variables With Asynchronous Geocode Function?
问题描述
我有位置对象的数组列表,我使用其中的一些构建一个完整的地址,然后地理code这一点。有一次,我收到了好状态,我再放置一个标记在地图上。这一切工作正常。不过,现在我也想将一个信息窗口上的每个标记从我的数组列表,LOCATIONNAME另一个属性。
code是在这里:
I have an array list of location objects, and I am using some of them to build a full address, and then geocode that. Once I receive the OK status I am then placing a marker on the map. This all works fine. However, now I would also like to place an info window on each marker with another property from my array list, LocationName. Code is here:
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);
}
});
}
}
警报是只看到LOCATIONNAME是什么,当我拿到身份确定。但在测试中它仅仅是总是相同的值。有一次,我可以根据这个每次体现正确的价值的话,我有code一字排开放置信息窗口上的标记。
The alert is to just see what locationName is when I get that status OK. But in testing it is just always the same value. Once I can tailor this to reflect the right value each time, then I have code lined up to place the info windows on the marker.
任何帮助将大大AP preciated!
Any help would be greatly appreciated!
推荐答案
最简单的事情可能是你的循环中创建一个局部范围的块,使LOCATIONNAME实际上是指的不同的的变量每次您添加一个委托/匿名函数做地理编码。在循环配售VAR不会产生变量的新实例,使用var声明基本上是被移动到封闭范围块的顶部。
The simplest thing is probably to create a local scope block within your loop so that locationName actually refers to a different variable for every time you add a delegate/anonymous function to do the geocoding. Placing the var in the loop does not create a new instance of the variable, the var declaration essentially gets moved to the top of the enclosing scope block.
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
})();
}
编辑:
或者,如果你使用一些框架/,使您可以通过一个匿名函数来执行code在一个阵列的每个项目,你会得到那样的问题作用域自动为您照顾。
Or if you were using some framework/ that allows you to pass an anonymous function to execute code for each item in an array, you get that kind of scoping issue taken care for you automatically.
这篇关于GMaps实现JS地理code:使用/传递变量异步地理code函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!