I've been struggling with this for a few hours now, and even after reading several examples on Stack I've been unable to get this working. It doesn't help that I'm a JS newbie.
I'm trying to retrieve information about an address from the Google Geocoder API, and then pass the object over to another function. Per my reading I understand that function I'm using to retrieve the information is asynchronous, and therefore I need to use a callback function to read it. However, when I attempt to do this I still get 'undefined' returned by my console. I know that the information is coming from Google fine, since when I use console.log() on the result object it returns correctly.
Anyways, here's what I'm working with:
function onSuccess(position) {
getLocationData(position, function(locationData) {
console.log(locationData);
});
}
function getLocationData(position, callback) {
geocoder = new google.maps.Geocoder();
var location = 'Billings,MT';
if( geocoder ) {
geocoder.geocode({ 'address': location }, function (results, status) {
if( status == google.maps.GeocoderStatus.OK ) {
return results[0];
}
});
}
callback();
}
Like I mentioned though, all I get with this is 'undefined'. If I put 'console.log(results[0])' above the getLocationData() return, the object returned is correct though. Any help would be much appreciated.
Your problem is, that you didn't connect the callback to the return. As the
geocode()
function itself is already asynchronous, thereturn
doesn't have any effect there. Instead you have to pass the values you are returning here directly to the callback-function. Like this: