【问题标题】:Why can't I get the geolocation just outside that function [duplicate]为什么我不能在该功能之外获得地理位置[重复]
【发布时间】:2015-10-17 06:59:06
【问题描述】:
function instate(loc)
{
    var a;
    var geocoder = new google.maps.Geocoder;
    var infowindow = new google.maps.InfoWindow
    geocoder.geocode({'location': loc}, function(results, status) {
        if (status === google.maps.GeocoderStatus.OK) {
          if (results[1]) {
            map.setZoom(5);
            var arrAddress = results[0].address_components;
            $.each(arrAddress, function (i, address_component) {
              if (address_component.types[0] == "administrative_area_level_1"){
              a =  address_component.short_name;
              console.log(a);   
              }     
              //return false; // break the loop   
            });        
          } else {
            window.alert('No results found');
          }
        } else {
          window.alert('Geocoder failed due to: ' + status);
        }
    });
}

上面的代码可以在控制台打印出'a'的正确值,但是当我将console.log(a)放在函数底部时,就像下面一样,它不能打印正确的值而只是打印出“未定义”,这是为什么呢?

function instate(loc)
{
    var a;
    var geocoder = new google.maps.Geocoder;
    var infowindow = new google.maps.InfoWindow
    geocoder.geocode({'location': loc}, function(results, status) {
        if (status === google.maps.GeocoderStatus.OK) {
          if (results[1]) {
            map.setZoom(5);
            var arrAddress = results[0].address_components;
            $.each(arrAddress, function (i, address_component) {
              if (address_component.types[0] == "administrative_area_level_1"){
              a =  address_component.short_name;

              }     
              //return false; // break the loop   
            });        
          } else {
            window.alert('No results found');
          }
        } else {
          window.alert('Geocoder failed due to: ' + status);
        }
    });
    console.log(a);
}

【问题讨论】:

标签: javascript google-maps-api-3 geolocation


【解决方案1】:

让我澄清一下您的代码中发生了什么。在instate 函数中,定义一个名为a 的变量,然后调用geocode,传递function 作为其第二个参数。在该函数中,您将值分配给a。但是,该函数在您定义它之后还没有被调用。定义function 和调用它是有区别的。由于function 是异步的,因此可以肯定的是console.log-ing 分配在function 中的值不会像您预期的那样运行。

【讨论】:

  • google.maps.event.addListener(markers[i], 'dragend', function(evt){ positionafter = {lat: parseFloat(evt.latLng.lat()), lng: parseFloat( evt.latLng.lng())}; instate(positionafter); });我像上面的代码一样在其他地方调用它,但是这两个版本的代码的行为不同......
  • 您调用 instate,但在 instate 内部,您具有我在回答中描述的行为。一旦定义了异步函数,它将作为回调执行。这意味着在执行之前将经过几毫秒。但是,您尝试在这些毫秒过去之前查看 a 的值。您可能希望在函数内部和函数之后使用 console.log(new Date())。你会看到函数外的日期比函数内的日期大。
  • 嗯......我还有一些问题......有没有像 .done/.fail 这样的东西可以在我的代码中使用?或者我该如何解决这个问题......
  • 很抱歉打扰你...但是我发现我对 Promise 有点困惑,你能帮我解决这个问题吗?
猜你喜欢
  • 1970-01-01
  • 2012-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多