无法从API获取数据
问题描述:
我想建立一个显示当地温度的网站,使用浏览器的导航功能来获取坐标,但似乎是,当我打电话给天气API时,我没有得到任何数据。我使用的API是这一个:https://fcc-weather-api.glitch.me/无法从API获取数据
var la;
var lg;
function getLocation() {
if (navigator.geolocation)
navigator.geolocation.getCurrentPosition(showPosition);
}
function showPosition(position) {
la= position.coords.latitude;
lg= position.coords.longitude;
}
getLocation();
var url="https://fcc-weather-api.glitch.me/api/current?lat=" + la + "&lon=" + lg;
fetch(url)
.then((resp) => resp.json())
.then(function(data) {
let api = data.main;
return authors.map(function(api) {
document.getElementById("temper").innerHTML=api.temp;
})
})
这里有一个的jsfiddle:https://jsfiddle.net/9cLkjg5e/
答
不知道你想什么用authors.map
位做的,但它是没有必要的。提取返回的数据对象的温度为data.main.temp
;
所以基本上改变这将解决您的代码
document.getElementById("temper").innerHTML = api.temp;
固定JS:
var la;
var lg;
function getLocation() {
if (navigator.geolocation)
navigator.geolocation.getCurrentPosition(showPosition);
}
function showPosition(position) {
la= position.coords.latitude;
lg= position.coords.longitude;
//document.getElementById("temper").innerHTML="Latitude:" + la;
// document.getElementById("icon").innerHTML="Longitude:" + lg;
}
getLocation();
var url="https://fcc-weather-api.glitch.me/api/current?lat=" + la + "&lon=" + lg;
fetch(url)
.then((resp) => resp.json())
.then(function(data) {
let api = data.main;
document.getElementById("temper").innerHTML = api.temp;
})
.catch(function(error) {
console.log("error: " + error);
});
<div class="container">
<center><h1 id="header">Weather App</h1></center>
</div>
<div class="container">
<p id="temper"></p>
</div>
答
在旁注中,变量LA和LG都没有填充在API调用的时间。您可以通过在getCurrentPosition()的成功回调中执行API调用来解决此问题。
感谢您的帮助。 'authors.map'应该是'api.map'。我忘了改变它。 – Daniel
@Daniel在这种情况下你不需要'map'函数,因为数据是一个对象,而不是数组。 – H77
是的,我明白了。它现在有用,谢谢! – Daniel