-
Notifications
You must be signed in to change notification settings - Fork 0
/
weather.js
59 lines (49 loc) · 1.53 KB
/
weather.js
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
50
51
52
53
54
55
56
57
58
59
const weather = document.querySelector(".js-weather");
const COORDS = 'coords';
const API_KEY = '4a8866f99be03478e1377fbfdcf1019b';
//'241051bf13976dd3ddf8b8d9f247255e'
//'4a8866f99be03478e1377fbfdcf1019b';
function getWeather(latitude, longitude) {
fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}&units=metric`)
.then(function(reponse){
return reponse.json();
}).then(function(json){
const temperature = json.main.temp;
const weatherText = json.weather[0]['main'];
const place = json.name;
weather.innerText = `${temperature}℃ ${weatherText} in ${place}`
});
}
function saveCoords(coordsObj){
localStorage.setItem(COORDS, JSON.stringify(coordsObj));
}
function handleGeoSuccess(position){
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
const coordsObj = {
latitude,
longitude
};
saveCoords(coordsObj);
getWeather(latitude, longitude);
}
function handleGeoError() {
console.log("Can't access geo location");
}
function askForCoords() {
navigator.geolocation.getCurrentPosition(handleGeoSuccess,handleGeoError);
}
function loadCoords(){
const loadedCords = localStorage.getItem(COORDS);
if(loadedCords === null){
askForCoords();
} else {
// get Weather
const parseCoords = JSON.parse(loadedCords);
getWeather(parseCoords.latitude, parseCoords.longitude);
}
}
function init() {
loadCoords();
}
init();