相关疑难解决方法(0)

如何从Google Maps JavaScript地理编码器回调中返回变量?

我正在使用谷歌地图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);
        }
      });
    }
  }
Run Code Online (Sandbox Code Playgroud)

打印出undefined

如果我做:

  var geocoder;
  function initialize() {
    geocoder = new google.maps.Geocoder();
    var …
Run Code Online (Sandbox Code Playgroud)

javascript google-maps asynchronous

28
推荐指数
2
解决办法
4万
查看次数

标签 统计

asynchronous ×1

google-maps ×1

javascript ×1