Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

javascript - Using a callback function with Google Geocode

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

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

1 Reply

0 votes
by (71.8m points)

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]);
      }
    });
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...