0

我正在尝试创建一个函数,该函数利用 Google Javascript V3 的地理编码功能并返回一个包含经度和纬度的数组。由于某种原因,没有使用该函数填充返回数组。谢谢你的帮助!

代码:

  function getCoords(address) {
    var latLng = [];
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        latLng.push(results[0].geometry.location.lat());
        latLng.push(results[0].geometry.location.lng());
        return latLng;
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }    
    });
  }

  var test_arr;    
  test_arr = getLatLng('New York');
  alert(test_arr[0] + ',' + test_arr[1]) // I'm getting a test_arr is undefined here.
4

2 回答 2

0

@Matt Ball 应该已经发布了答案。:) test_arr 未定义的原因是因为您在结果返回之前立即对其进行评估。

如果你做了一个 setTimeout (你不应该这样做),你最终会注意到数组中会有一些东西。

setTimeout(function(){
   alert(test_arr) // has stuff...
}, 5000);

相反,您可以将匿名函数作为回调传递给 getCoords。一旦坐标可用,该函数就会被执行。

function getCoords(address, callback) {
    ...
    var lng = results[0].geometry.location.lng();
    var lat = results[0].geometry.location.lat();
    callback([lat, lng]);
    ...
}

getCoords("New York", function(coords) {
  alert(coords); // works
});
于 2013-02-10T03:49:25.997 回答
0

阅读在 Javascript 中使用回调函数。这篇文章可能会有所帮助。

正如 Jon 指出的那样,您可以通过将回调函数传递给 getCoords 方法来解决此问题。这是等待谷歌回复的一种方式。您定义一个将在地理编码完成时调用的函数。您将使用数据作为参数调用提供的函数,而不是返回数据。

像这样的东西:

function getCoords(address, callback) {
  var latLng = [];
  var geocoder = new google.maps.Geocoder();
  geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      latLng.push(results[0].geometry.location.lat());
      latLng.push(results[0].geometry.location.lng());
      callback(latLng);
    } else {
      alert("Geocode was not successful for the following reason: " + status);
    }    
  });
}

getCoords('New York', function(latLng) {
  var test_arr;
  test_arr = latLng;
  alert(test_arr[0] + ',' + test_arr[1])
  // Continue the rest of your program's execution in here
});
于 2013-02-10T04:03:28.103 回答