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,
//how can I also add the name of the building to the title attribute?
title: results[0].formatted_address
});
}
The Geocoding API uses a pay-as-you-go pricing model. Geocoding API requests generate calls to one of two SKUs depending on the type of request: basic or advanced. Along with the overall Google Terms of Use, there are usage limits specific to the Geocoding API.
positionstack - Free Address Geocoding & Maps API.
Enable Geocoding API In your Google Cloud Platform Console, go to APIs & Services → Dashboard → Enable APIs & Services at the top and choose Maps JavaScript API from the API Library. This will open up the Maps JavaScript API page and Enable it.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With