Google Maps API v3 - Pass more information into GeoCode Call back?
I'm working with Google Maps API v3 to geocode addresses. How do I pass additional information into the geocodeCallBack function? See my code & comments below to understand what I'm trying to achieve.
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,
/开发者_JS百科/how can I also add the name of the building to the title attribute?
title: results[0].formatted_address
});
}
Make a closure makeCallback
of the geocodeCallBack
. The closure gets and keeps the 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;
}
Of course, you could also make a closure makeCallback(addressName)
and pass the name directly, but the above version with the address index is more general.
精彩评论