【问题标题】:how to return a variable outside of javascript function that is inside a function?如何在函数内部的javascript函数之外返回一个变量?
【发布时间】:2012-01-02 03:28:33
【问题描述】:

所以我有

  function find_coord(lat, lng) {
              var smart_loc;
      var latlng = new google.maps.LatLng(lat, lng);
        geocoder = new google.maps.Geocoder();
        geocoder.geocode( { 'latLng': latlng }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                smart_loc = new smart_loc_obj(results);
            } else {
                smart_loc = null;
            }
        });

        return smart_loc;
}

我想返回 smart_loc 变量/对象,但它始终为 null,因为函数(结果、状态)的范围未达到 find_coord 函数中声明的 smart_loc。那么如何将函数内部的变量(results, status)取出来呢?

【问题讨论】:

  • 我认为这不是范围问题。而是一个我尚未定义的问题。 geocoder.geocode 是做什么的?类似于 AJAX 调用?
  • 你不能那样做。 “geocode()”函数是异步,也就是说它不会立即运行;它在 Google 返回结果时运行。
  • 但直到函数运行后地理编码才会运行,并且地理编码器来自谷歌地图地理编码器
  • 地理编码调用的回调函数在 Google 响应您的请求时运行。它不是同步的;它可能会在您的“geocode()”函数运行后很多毫秒发生。

标签: javascript google-maps google-geocoder


【解决方案1】:

你可以这样做:

var smart_loc;

function find_coord(lat, lng) {
  var latlng = new google.maps.LatLng(lat, lng);
    geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'latLng': latlng }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            smart_loc = new smart_loc_obj(results);
        } else {
            smart_loc = null;
        }
    });
}

或者如果你需要在 smart_loc 改变时运行一个函数:

function find_coord(lat, lng, cb) {
          var smart_loc;
  var latlng = new google.maps.LatLng(lat, lng);
    geocoder = new google.maps.Geocoder();
    geocoder.geocode( { 'latLng': latlng }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            smart_loc = new smart_loc_obj(results);
        } else {
            smart_loc = null;
        }

        cb(smart_loc);
    });
}

然后调用:

find_coord(lat, lng, function (smart_loc) {
    //
    // YOUR CODE WITH 'smart_loc' HERE
    //
});

【讨论】:

    猜你喜欢
    • 2017-06-01
    • 2014-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-21
    • 2023-02-23
    • 1970-01-01
    相关资源
    最近更新 更多