Search code examples
javascriptjquerygoogle-geolocation

Undefined Issue using Google's Javascript API


I've been stuck on an issue for a number of days when using the google geo-location api. This is what I've been trying -

function codeAddress(address) {
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({"address": address}, function(results, status) {
        if (status == "OK") {
            return results[0].geometry.location;
        } else {
            return null;
        }
    });
}

function generateJSON(origin, destination) {
    var origin_loc = codeAddress(origin);
    var dest_loc = codeAddress(destination);
    ....
}

The "origin_loc" variable is coming back unassigned and I haven't been able to figure out why with the debugger. When I log the results[0] to the console it is coming back fine with the object.

Does anyone have any ideas why this is happening?

Thanks


Solution

  • This is what worked for me in the end -

    function codeAddresses(addresses, callback) {
        var coords = [];
        for(var i = 0; i < addresses.length; i++) {
            var geocoder = new google.maps.Geocoder();
            geocoder.geocode({'address':addresses[i]}, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    coords.push(results[0].geometry.location);
                    if(coords.length == addresses.length) {
                        callback(coords);
                    }
                }
                else {
                    throw('No results found: ' + status);
                }
            });
        }
    }
    
    function generateJSON(origin, destination) {
        var addresses = [origin, destination];
        codeAddresses(addresses, function(coords) {
             var json = { ..... }
             ....
        });
    }
    

    Thanks for your help @yuriy636!