Reputation: 549
I want to build a website which displays the local temperature, using the browser's navigator feature to get the coordinates, but it seems that, when I call the weather api, I don't get any data. The api that I used is this one: https://fcc-weather-api.glitch.me/
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;
})
})
Here's a jsfiddle: https://jsfiddle.net/9cLkjg5e/
Upvotes: 2
Views: 1106
Reputation: 1
On a sidenote, the variables la and lg are not filled at the time of the API call. You could solve this by doing the API call in the success callback of the getCurrentPosition().
Upvotes: 0
Reputation: 5967
Not sure what you're trying to do with the authors.map
bit but it isn't necessary. The data object returned by the fetch has the temperature in data.main.temp
;
So basically changing to this would fix your code
document.getElementById("temper").innerHTML = api.temp;
Fixed 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>
Upvotes: 2