I'm using the openweathermap.org API, and am using javascript to fetch the data, then post to HTML. I have two javascript functions. One function for getting the current weather is working really well - the second function is pulling the 5 day forecast. I have gotten to the point where I can pull the data, but I need to loop through that data and post to HTML. Here's the function:
function getForecast() {
let forecast_icon = document.getElementById("forecast_icon");
let forecast_temperature = document.getElementById("forecast_temperature");
let api = "https://api.openweathermap.org/data/2.5/weather";
let apiKey = "API KEY";
location.innerHTML = "Locating...";
navigator.geolocation.getCurrentPosition(success, error);
function success(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
let url = api + "?lat=" + latitude + "&lon=" + longitude + "&appid=" + apiKey + "&units=imperial";
fetch(url)
.then(response => response.json())
.then(forecast => {
console.log(forecast);
let temp = forecast.main.temp;
forecast_temperature.innerHTML = Math.round(temp) + "°F";
let icon = forecast.weather[0].icon;
forecast_icon.innerHTML = '<img src="http://openweathermap.org/img/wn/' + icon + ".png" + '"/>';
});
}
function error() {
location.innerHTML = "Unable to retrieve your location";
}
}
getForecast();
Here's the HTML - it's quite simple:
<ul>
<li>
<div id='forecast_icon'></div>
<div class='temperature-sensor-day' id='forecast_temperature'></div>
</li>
</ul>
I'm not sure how to loop through the data and post each result to the HTML. I'll keep searching but would appreciate some guidance.
Edit:
I need to loop through the output of the API calls and post that data into the HTML shown above.
I tried working with "promises". I saw this in my searches:
for (url in urls){
time = getData(urls[url])
console.log(time)
ttTimes.push(time)
};
I tried substituting my values but since this one uses two url's I couldn't work out how to make it work.
I've also seen different types of loops so I'm getting confused on the best way to do this.
Below is a picture of what it looks like. You can see that only one of the five days are populating. Hopefully that helps visualize the problem.