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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2993563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:49:53  来源:igfitidea点击:

How do I return a variable from Google Maps JavaScript geocoder callback?

javascriptgoogle-mapsasynchronous

提问by bmck

I am working with the google maps API and whenever I return the variable to the initialize function from the codeLatLng function it claims undefined. If I print the variable from the codeLatLng it shows up fine.

我正在使用谷歌地图 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);
        }
      });
    }
  }

prints out undefined

打印出未定义

If I do:

如果我做:

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

prints out New York, NY 10012, USA

打印出纽约,NY 10012,美国

回答by Guffa

You can't return the value from the function, the value doesn't exist yet when the function returns.

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

The geocodemethod makes an asynchonous call and uses a callback to handle the result, so you have to do the same in the codeLatLngfunction:

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

回答by Rob

You're making an asynchronous request, your codeLatLng()function has finished and returned long before the geocoder is done.

您正在发出异步请求,您的codeLatLng()函数在地理编码器完成之前很久就已完成并返回。

If you need the geocoder data to continue, you'll have to chain your functions together:

如果需要继续使用地理编码器数据,则必须将函数链接在一起:

function initialize() {
    geocoder = new google.maps.Geocoder();
    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]) {
                        initContinued(results[1].formatted_address);
                    } else {
                        alert("No results found");
                    }
                } else {
                    alert("Geocoder failed due to: " + status);
                }
        });
      }

}
function initContinued(addr) {
    alert(addr);
}

回答by vino

You can get value using localstorage.

您可以使用 localstorage 获取价值。

 geocoder.geocode({
            'address': address,             
        }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                var latitude = results[0].geometry.location.lat();
                var longitude = results[0].geometry.location.lng();
            }                             
           localStorage.setItem("endlat", latitude);
           localStorage.setItem("endlng", longitude);
            });
var end_lat = localStorage.getItem("endlat");
var end_lng = localStorage.getItem("endlng");

But it returns previous value.. Returns current value when we click twice...

但它返回以前的值.. 当我们单击两次时返回当前值...

回答by resopollution

pass geocoder as a parameter to the codeLatLng() function.

将 geocoder 作为参数传递给 codeLatLng() 函数。

function codeLatLng(geocoder) {

call it like so in your initialize function:

在初始化函数中像这样调用它:

var addr = codeLatLng(geocoder);

回答by Bobby Hyman

That return is not returning from codeLatLng; it's returning from the anonymous function being passed to geocoder.geocode.

那个回报不是从codeLatLng; 它从传递给的匿名函数返回geocoder.geocode

I think you'll need to pass the data using another mechanism e.g. a global variable

我认为您需要使用另一种机制(例如全局变量)传递数据