Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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,
            //how can I also add the name of the building to the title attribute?
            title: results[0].formatted_address
        });
}
like image 837
John Avatar asked Aug 09 '11 21:08

John


People also ask

Is Google reverse geocoding API free?

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.

Is there any free geocoding API?

positionstack - Free Address Geocoding & Maps API.

How do I use Google API for geocoding?

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.


1 Answers

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.

like image 93
Jiri Kriz Avatar answered Oct 11 '22 12:10

Jiri Kriz