2014-10-02 45 views
0

为什么我无法获得此代码的坐标?无法从此代码中获取纬度和经度

错误是:ReferenceError: Can't find variable: card_Latitude

我把代码从这里:How to get longitude and latitude of a city/country inputted through an input box?

我不明白为什么。

<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> 
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script> 
<script> 
    var card_FullAddress = "Canada"; 

    var geocoder = new google.maps.Geocoder(); 
    geocoder.geocode({ 
     'address': card_FullAddress 
    }, function(results, status) { 
     if (status == google.maps.GeocoderStatus.OK) { 
      var card_Latitude = results[0].geometry.location.lat(); 
      var card_Longitude = results[0].geometry.location.lng(); 
     } else { 
      var card_Latitude = "ERR"; 
      var card_Longitude = "ERR"; 
     } 
    }); 

    console.log(card_Latitude); 
    console.log(card_Longitude); 
</script> 

JS FIDDLE

+1

因为'card_Latitude'是** **本地的回调函数。如果你仔细观察,你会注意到你把'console.log' *放在回调的外部。这是一个更简单的例子:'function foo(){var bar = 42; };的console.log(巴);'。看起来你对异步代码不熟悉,所以我推荐阅读:http://stackoverflow.com/q/23667086/218196 – 2014-10-02 15:31:05

+1

'card_Latitude'存在于不同的范围内。 – gdoron 2014-10-02 15:31:36

+0

那么如何在外面访问它呢?我试图删除'var',但同样的错误。 – Bonito 2014-10-02 15:32:57

回答

0
var card_FullAddress = "Canada"; 

var geocoder = new google.maps.Geocoder(); 
geocoder.geocode({ 
    'address': card_FullAddress 
}, function(results, status) { 
    if (status == google.maps.GeocoderStatus.OK) { 
     var card_Latitude = results[0].geometry.location.lat(); 
     var card_Longitude = results[0].geometry.location.lng(); 

     //Lat and long are only available in this scope! continue your code here! 
     console.log(card_Latitude); 
     console.log(card_Longitude); 
    } else { 
     var card_Latitude = "ERR"; 
     var card_Longitude = "ERR"; 
    } 
}); 
+0

如果我需要,我如何在外面访问它们? – Bonito 2014-10-02 15:39:05

+0

简答题;你不能。你可以做的就是使用像[异步](https://github.com/caolan/async)这样的库来让你的代码更清晰并避免回调地狱。您应该Google for JavaScript异步代码和谷歌/ StackOverflow回调更详细的解释。 – renatoargh 2014-10-02 15:42:11

+1

@Bonito:您可以在更高的范围内声明变量,例如在全球范围内。异步代码的问题不是范围,而是时间。即使您将变量设置为全局可用,您也不会在分配值时分配。你只知道什么时候回调被调用。鉴于这种不确定性,将这些变量全球化并没有多大用处。你真的应该花一些时间阅读你对问题的评论中的所有链接,以更好地理解整个主题。 – 2014-10-02 15:42:13