Javascript 在Google Geocode中使用回调函数

Javascript 在Google Geocode中使用回调函数,javascript,ajax,function,asynchronous,geocoding,Javascript,Ajax,Function,Asynchronous,Geocoding,我已经为此挣扎了几个小时,甚至在阅读了堆栈上的几个示例之后,我仍然无法让它工作。我是个JS新手,这没用 我试图从GoogleGeocoderAPI中检索有关地址的信息,然后将该对象传递给另一个函数。根据我的阅读,我知道我用来检索信息的函数是异步的,因此我需要使用回调函数来读取它。然而,当我尝试这样做时,我的控制台仍然返回“undefined”。我知道这些信息来自Google fine,因为当我对结果对象使用console.log()时,它会正确返回 不管怎样,我的工作是: function on

我已经为此挣扎了几个小时,甚至在阅读了堆栈上的几个示例之后,我仍然无法让它工作。我是个JS新手,这没用

我试图从GoogleGeocoderAPI中检索有关地址的信息,然后将该对象传递给另一个函数。根据我的阅读,我知道我用来检索信息的函数是异步的,因此我需要使用回调函数来读取它。然而,当我尝试这样做时,我的控制台仍然返回“undefined”。我知道这些信息来自Google fine,因为当我对结果对象使用console.log()时,它会正确返回

不管怎样,我的工作是:

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

就像我提到的,我得到的只是“未定义”。如果我将“console.log(results[0])放在getLocationData()返回的上方,则返回的对象是正确的。任何帮助都将不胜感激。

您的问题是,您没有将回调连接到返回。由于
geocode()。相反,您必须将返回的值直接传递给回调函数。像这样:

函数getLocationData(位置,回调){ geocoder=新的google.maps.geocoder(); var位置='比林斯,MT'; if(地理编码器){ geocoder.geocode({'address':location},函数(结果,状态){ if(status==google.maps.GeocoderStatus.OK){ 回调(结果[0]); } }); } }
Max,你是救命恩人!非常感谢!可能重复的