0

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

sgpbyrne
  • 565
  • 1
  • 7
  • 13
  • I guess that google geocoder works with AJAX internally, so you can't `return` a value, because it's asynchronous, check http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – yuriy636 Aug 14 '16 at 19:02
  • @yuriy636 - thanks, that seems like a good guess to me - ill look into it. Nothing is as easy as it first seems!! – sgpbyrne Aug 14 '16 at 19:14
  • tried - codeAddress(origin).done(function(response) {origin_loc=response;}); but that's causing codeAddress function to be undefined. – sgpbyrne Aug 14 '16 at 19:31
  • 1
    You need to call generateJSON from inside `function(results, status) {` (its called a callback). That way it will be called after the results are obtained from the geocode request. | Check the Google's demo: it makes changes (like the map's marker position) inside the callback https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple?hl=en – yuriy636 Aug 14 '16 at 19:46
  • Ahh OK I know what you mean now. The problem with that is that I need to do it for two different addresses before I can generate the JSON. So I can't do all of that within the callback. – sgpbyrne Aug 14 '16 at 20:02

1 Answers1

0

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!

sgpbyrne
  • 565
  • 1
  • 7
  • 13