【发布时间】:2016-06-07 22:09:37
【问题描述】:
我正在使用 openweather api 来显示用户所在城市的天气。我首先使用地理定位功能来查找用户的纬度和经度。然后将该数据传递到变量 api 中。控制台一直显示未定义的值。我不确定我哪里出错了。
这里是 JavaScript:
$(document).ready(function(){
var lat;
var long;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
lat = position.coords.latitude;
long = position.coords.longitude;
var api='http://api.openweathermap.org/data/2.5/weather?lat='+lat+'&lon='+long+'&appid=myapi';
$.getJSON(api,function(data){
var city= data.name;
console.log(api);
console.log(city);
});
});
}
});
【问题讨论】:
-
您测试过您的 API 密钥吗?把网址放在浏览器中看看会出现什么? api.openweathermap.org/data/2.5/… 如果它返回如下内容: {"cod":401, "message": "Invalid API key. Please see openweathermap.org/faq#error401 for more info."} 那么你需要仔细检查你的 appid
-
这是准确的代码吗?也许您忘记用您从 openweather 获得的实际 appId 替换 myapi。我问是为了以防万一。
-
这是准确的代码减去实际的 api 密钥号。
-
酷,你在浏览器中测试了 URL 吗?并且还在 var city=data.name 之前放置一个 console.log(data) ,看看服务返回了什么。
-
这是我的 codepen 的链接:codepen.io/sibraza/pen/VjYwWK?editors=1111
标签: javascript jquery openweathermap