【发布时间】:2017-01-20 21:25:10
【问题描述】:
我正在尝试使用 API 显示当地天气。 API url 根据用户的本地位置生成。
var lat,lon = null;
var key = "mykey";
var api = "";
function setApi(position){
lat = Math.round(position.coords.latitude*1000)/1000;
lon = Math.round(position.coords.longitude*1000)/1000;
api = "http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&appid=" + key;
}
navigator.geolocation.getCurrentPosition(setApi);
$.getJSON(api, function(data){
console.log(data.sys.country);
});
如果我使用我的 api 全局变量作为 $.getJSON 函数的参数,问题就不会发生。如果我改用字符串,它会起作用。例如:
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=46.295&lon=30.648&appid=%mykey%", function(data){
console.log(data.sys.country);
});
【问题讨论】:
-
所以我想说
api不是您在通话时认为的那样。我猜它仍然是""。例如,可能getCurrentPosition失败..(或者可能是异步的..我不熟悉) -
getCurrentPosition没有失败。我可以通过控制台访问我的 api var,它具有正确的价值。我猜异步可能是问题所在。谢谢。 -
尝试在设置
api值之后将调用移至然后,如果你确定它可以达到那么远 -
你是对的,它现在可以工作了。非常感谢。
标签: javascript jquery