javascript - 如何从 Google map JavaScript 地理编码器回调返回变量?

标签 javascript google-maps asynchronous

我正在使用谷歌地图API,每当我将变量从codeLatLng函数返回到初始化函数时,它都会声明未定义。如果我从 codeLatLng 打印变量,它会显示得很好。

  var geocoder;
  function initialize() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(40.730885,-73.997383);
    var addr = codeLatLng();
    document.write(addr);

  }

  function codeLatLng() {
    var latlng = new google.maps.LatLng(40.730885,-73.997383);
    if (geocoder) {
      geocoder.geocode({'latLng': latlng}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          if (results[1]) {
                return results[1].formatted_address;
          } else {
            alert("No results found");
          }
        } else {
          alert("Geocoder failed due to: " + status);
        }
      });
    }
  }

打印出未定义

如果我这样做:

  var geocoder;
  function initialize() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(40.730885,-73.997383);
    codeLatLng();


  }

  function codeLatLng() {
    var latlng = new google.maps.LatLng(40.730885,-73.997383);
    if (geocoder) {
      geocoder.geocode({'latLng': latlng}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          if (results[1]) {
                document.write(results[1].formatted_address);
          } else {
            alert("No results found");
          }
        } else {
          alert("Geocoder failed due to: " + status);
        }
      });
    }
  }

打印出 New York, NY 10012, USA

最佳答案

您无法从函数返回值,函数返回时该值还不存在。

geocode 方法进行异步调用并使用回调来处理结果,因此您必须在 codeLatLng 函数中执行相同的操作:

var geocoder;
function initialize() {
  geocoder = new google.maps.Geocoder();
  var latlng = new google.maps.LatLng(40.730885,-73.997383);
  codeLatLng(function(addr){
    alert(addr);
  });
}

function codeLatLng(callback) {
  var latlng = new google.maps.LatLng(40.730885,-73.997383);
  if (geocoder) {
    geocoder.geocode({'latLng': latlng}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (results[1]) {
          callback(results[1].formatted_address);
        } else {
          alert("No results found");
        }
      } else {
        alert("Geocoder failed due to: " + status);
      }
    });
  }
}

关于javascript - 如何从 Google map JavaScript 地理编码器回调返回变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2993563/

相关文章:

php - 验证,每行多个单选按钮

javascript - 在使用 Handlebars.js 进行模板化时处理带有 UUID 键的 JSON 对象?

javascript - 从谷歌javascript api获取特定语言的纬度、经度城市名称

android - 谷歌地图 Intent - 避开高速公路和收费站? (安卓)

c# - 使用 async/await 和 TaskCompletionSource 的奇怪堆栈跟踪增长

javascript - 如何从列表底部的 3 个 3 个选定列表中删除值

javascript - 无法按类 Selenium 亚马逊找到元素

google-maps - map 初始化后是否可以更改 Google map 样式?

C# 多个任务在调用行上被阻止

python - zeromq zmq.Poller & 标准输入