javascript - 如何返回函数内部的javascript函数外部的变量?

标签 javascript google-maps google-geocoder

所以我有

  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。那么怎么把函数内部的一个变量(结果,状态)取出来呢?

最佳答案

你可以这样做:

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

关于javascript - 如何返回函数内部的javascript函数外部的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8697164/

相关文章:

jquery - 如何从位置(x,y)获取谷歌地图v3上的位置(纬度/经度)

javascript - 谷歌地理编码,异步Javascript,不起作用

json - 如何将 google Geocoding API 结果映射到简单的城市、地区、国家

javascript - 从父元素中删除文本但不删除附加元素

javascript - 遍历一组键/值对以设置值

google-maps - 谷歌地图 api 带有信息窗口的多个标记

curl - Google 地理编码服务返回错误 400 错误请求

javascript - React 功能组件 useEffect 钩子(Hook)在类组件生命周期中具有相等的依赖性

javascript - 网站的嵌入式覆盖聊天

angularjs - 将鼠标悬停在标记上时的 Angular 谷歌地图信息窗口/工具提示