我正在使用Google Maps API v3进行地理编码地址。如何将其他信息传递到geocodeCallBack函数?看我的代码&下面的评论,以了解我想要实现的目标。
var address = new Array();
address[0] = {name:'Building 1',address:'1 Smith Street'};
address[1] = {name:'Building 2',address:'2 Smith Street'};
for(var rownum=0; rownum<=address.length; rownum++)
{
if(address[rownum])
geocoder.geocode( {'address': address[rownum].address}, geocodeCallBack);
}
function geocodeCallBack(results, status)
{
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
//how can I also add the name of the building to the title attribute?
title: results[0].formatted_address
});
}
答案 0 :(得分:23)
制作makeCallback
的约geocodeCallBack
。闭包获取并保持rownum
:
for (var rownum=0; rownum<=address.length; rownum++) {
if (address[rownum])
geocoder.geocode( {'address': address[rownum].address}, makeCallback(rownum));
}
function makeCallback(addressIndex) {
var geocodeCallBack = function(results, status) {
var i = addressIndex;
alert(address[i].name + " " + results[0].formatted_address);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
// use address[i].name
title: results[0].formatted_address
});
}
return geocodeCallBack;
}
当然,您也可以创建一个闭包makeCallback(addressName)
并直接传递名称,但上面带有地址索引的版本更为通用。