【发布时间】:2017-09-28 20:23:08
【问题描述】:
我正在尝试使用 FCC 项目中的 javascript 制作一个天气显示应用程序。为了首先显示当前天气,我必须找到设备的位置。使用 HTML 地理位置可以正常工作。但是当我尝试在函数外部使用它时,纬度和经度给了我undefined 错误,即使我试图将它分配给全局变量。
$(document).ready(function(){
var lon;
var lat;
function getLocation(){
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(showPosition);
}
else{
console.log("your device is not suported!");
}}
function showPosition(position){
var pos = position.coords
lat = pos.latitude;
lon = pos.longitude;
}
console.log(lat); // for debugging, here is the undefined error
$.ajax({
type: 'GET',
url: 'https://fcc-weather-api.glitch.me/api/current?lat=35&lon=139',
success: function(data){
$('h1').html( "<strong>" + data.coord.lat + "</strong>" );
console.log(latitude);
},
error: function(error){
console.log(error);
}
});
});
感谢您的帮助:)
【问题讨论】:
-
您的代码中有一个未定义的“纬度”。请参阅 Ajax 的成功函数中的
console.log(latitude);。也许将其更改为data.coord.lat(如上一行)。
标签: javascript jquery ajax