0

对不起,我知道这已经被问了一千次了,但我已经阅读了回复,但我仍然不明白。我是 Javascript 新手(实际上是昨天开始的),我遇到了以下问题:

我有一个异步函数,我需要返回值,但它当然是未定义的。我读过回调,但我不确定它们是如何工作的。

功能如下:

function getLatLong(address){
      var geo = new google.maps.Geocoder;

      geo.geocode({'address':address},function(results, status){
              if (status == google.maps.GeocoderStatus.OK) {

                var returnedLatLng = [];
                returnedLatLng["lat"] = results[0].geometry.location.lat();
                returnedLatLng["lgn"] = results[0].geometry.location.lng();
                locationTarget = new google.maps.LatLng(returnedLatLng.lat,returnedLatLng.lgn);
                alert(locationTarget);
                return locationTarget;
              } else {
                alert("Geocode was not successful for the following reason: " + status);
              }

       });
  }

我从一个 initialize() 函数调用这个函数,我这样做是这样的:

var location = getLatLong(address);

好吧,我的问题是回调如何帮助我?如果可能的话..我应该使用什么代码?

非常感谢!(这是我在这里的第一个第一个问题!)

4

2 回答 2

0

最基本的解决方案是在全局范围内定义您的位置并响应您已经拥有的回调:

var location;
function getLatLong(address){
      var geo = new google.maps.Geocoder;

      geo.geocode({'address':address},function(results, status){
              if (status == google.maps.GeocoderStatus.OK) {

                var returnedLatLng = [];
                returnedLatLng["lat"] = results[0].geometry.location.lat();
                returnedLatLng["lgn"] = results[0].geometry.location.lng();
                locationTarget = new google.maps.LatLng(returnedLatLng.lat,returnedLatLng.lgn);
                alert(locationTarget);
                location = locationTarget;
                // Additional logic you are using the location for
                // After this point your location is defined.
              } else {
                alert("Geocode was not successful for the following reason: " + status);
              }

       });
  }
 getLatLong(address)

所以基本上你的逻辑不需要基于对返回位置的这个方法的调用,而是基于调用geocode函数回调之后发生的事情。

于 2013-10-11T13:51:02.553 回答
0

尝试这个:

var locationCallback = function(location){
        // your fancy code here
    };
function getLatLong(address){
      var geo = new google.maps.Geocoder;

      geo.geocode({'address':address},function(results, status){
              if (status == google.maps.GeocoderStatus.OK) {

                var returnedLatLng = [];
                returnedLatLng["lat"] = results[0].geometry.location.lat();
                returnedLatLng["lgn"] = results[0].geometry.location.lng();
                locationTarget = new google.maps.LatLng(returnedLatLng.lat,returnedLatLng.lgn);
                alert(locationTarget);

                //this is your callback
                locationCallback(locationTarget);


              } else {
                alert("Geocode was not successful for the following reason: " + status);
              }

       });
  }
 getLatLong(address)
于 2013-10-11T13:57:30.420 回答