Search code examples
javascriptgoogle-maps-api-3google-geocoder

How to pass ID for geocoding request


I am working on a little API, which should display markers on Google Maps. I have a database of possible markers, where I need to set longitude and latitude of the address so I can show them later on the map, without doing geocoding each time for all addresses.

I made a little utility to run it one time and cache these necessary data into database:

function processMissing(data) {
    var result;

    geocoder = new google.maps.Geocoder();
    for (var i=0;i<data.length;i++) {
        geocoder.geocode( { 'address' : data[i]['address']+','+data[i]['city']+','+data[i]['zipcode']+','+data[i]['ctrcode']}, function(results, status) {
            if (status === google.maps.GeocoderStatus.OK) {
               result = data[i]['id'] + ': ' + results[0].geometry.location);
               //Store result to database
            }
        });
    }
}

My only problem is, that data[i]['id'] will of course throw data[i] undefined error, because it does not exists inside of function, which is called async when geocoder is done.

Question is, how can I pass this ID trough geocoder.geocode or how can I reach him inside of function?

Thank you for your help in advance!


Solution

  • Use function closure to associate the id with the callback:

    function geocodeAddress(data) {
            geocoder.geocode( { 'address' : data['address']+','+data['city']+','+data['zipcode']+','+data['ctrcode']}, function(results, status) {
                if (status === google.maps.GeocoderStatus.OK) {
                   // save the result data in the input structure or write it to your database
                   data['id'].result = data['id'] + ': ' + results[0].geometry.location);
                   //Store result to database
                } else alert("id ="+data['id']+" could not be geocoded, status:"+status);
            });
    }
    
    function processMissing(data) {
        var result;
    
        geocoder = new google.maps.Geocoder();
        for (var i=0;i<data.length;i++) {
          geocodeAddress(data[i])
        }
    }