Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
184 views
Welcome To Ask or Share your Answers For Others

1 Answer

Your problem is, that you didn't connect the callback to the return. As the geocode() function itself is already asynchronous, the return doesn't have any effect there. Instead you have to pass the values you are returning here directly to the callback-function. Like this:

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 ) {
        callback(results[0]);
      }
    });
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...