小编典典

如何从Google Maps JavaScript geocoder回调返回变量?

javascript

我正在使用Google Maps
API,并且每当我从codeLatLng函数将变量返回到initialize函数时,它都声明未定义。如果我从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);
        }
      });
    }
  }

打印出美国纽约州纽约10012


阅读 341

收藏
2020-05-01

共1个答案

小编典典

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

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);
      }
    });
  }
}
2020-05-01