【发布时间】:2016-02-28 11:20:21
【问题描述】:
编辑:刚刚完成了这个项目。新链接在这里! http://codepen.io/myleschuahiock/full/pyoZge/
我正在为我的免费代码营制作天气小部件应用程序。除“城市”外的所有内容都是静态占位符。我正在使用 Open Weather Api,它使我们知道纬度和经度。出于调试目的,我将我所在区域的经度和纬度放在时间占位符下方。
我的问题是,当我在 API 链接上静态输入纬度和经度时,它工作得很好。它返回我居住的附近城市“曼达卢永市”:
http://api.openweathermap.org/data/2.5/weather?lat=14.603814400000001&lon=121.04907589999999&id=524901&APPID=ca8c2c7970a09dc296d9b3cfc4d06940
但是当我这样做时,我会在其中动态添加 mylatitude 和 mylongitude,以完成 API 链接:
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=" + mylatitude + "&lon=" + mylongitude + "&id=524901&appid=ca8c2c7970a09dc296d9b3cfc4d06940", function(json) {
$('.city').html(json.name);
我总是把“莫斯科”作为我的城市。
请在此处仔细查看我的 Javascript/JQuery 代码! http://codepen.io/myleschuahiock/pen/zqYzWm?editors=0010
非常感谢!非常感谢!
【问题讨论】:
-
您的代码不起作用的原因是
navigator.geolocation.getCurrentPosition是异步的。因此,您在实际确定位置之前致电$.getJSON。最简单的解决方案是将getJSON移动到navigator.geolocation.getCurrentPosition回调中 -
@JaromandaX 或将
getJSON移动到 if 条件中,因为您只想在客户端允许该位置时运行 API。 :P -
@NewToJS - 你的建议让我感到困惑...... if 条件在我所指的回调之外 - 为什么我要在回调之前或之后放置 getJSON,会发生完全相同的问题
-
@JaromandaX 看看我的回答。替换 OP 的 codepen 中的 javascript 并将其替换为我发布的那个。
-
@NewToJS - 你的回答完全符合我的建议......将getJSON调用放在
getCurrentPosition的回调中 - 你继续让我感到困惑
标签: javascript jquery json geolocation