18. Weather App

Checking the weather near you...

HTML

1
<div id="app">Checking the weather near you...</div>

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/* For today’s project, we’re going to build an app that gets a user’s location
and displays their current weather information. */

const app = document.querySelector('#app');
const apiKeyIp = 'd9f7add9f68440818a0659381720a532';
const apiKeyWeather = '5e995a3338fe2917188f0f98d08abcec';
let userCity;

const render = function (icon, temp, city, sky) {
app.innerHTML = (`
<div class="weather_container">
<div class="weather_icon"><img src="http://openweathermap.org/img/wn/${icon}@2x.png"></div>
<h3 class="weather_temperature">${Math.round(temp)} &#x2103;</h3>
<h4 class="weather_city-name">${city}</h4>
<p class="weather_desc">${sky}</p>
</div>
`)
};

const getWeatherInfo = function () {
fetch(`https://api.ipgeolocation.io/ipgeo?apiKey=${apiKeyIp}`).then(function (response) {
if (response.ok) {
return response.json();
} else {
return Promise.reject(response);
}
}).then(function (data) {
userCity = data.city;
return fetch(`http://api.openweathermap.org/data/2.5/weather?q=${userCity}&appid=${apiKeyWeather}&units=metric`);
}).then(function (response) {
if (response.ok) {
return response.json();
} else {
return Promise.reject(response);
}
}).then(function (userData) {
userIcon = userData.weather[0].icon;
userTemp = userData.main.temp;
userCity = userData.name;
userSky = userData.weather[0].description;

render(userIcon, userTemp, userCity, userSky);
}).catch(function (err) {
console.warn(err);
app.textContent = "Something went wrong...";
})
}

getWeatherInfo();