-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweather.js
68 lines (56 loc) · 1.68 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
60
61
62
63
64
65
66
67
68
const API_KEY = "008a55bdb0cf43d2eaa9f72e2f0eba20";
const weather = document.querySelector(".js-weather");
const COORDS = "coords";
function getWeather(lat, lng){
fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lng}&appid=${API_KEY}&units=metric`
).then(function(response){
return response.json();
}).then(function(json){
// console.log(json);
const temperature = json.main.temp;
const place= json.name;
weather.innerText = `${temperature} @${place}`;
});
}
function saveCoords(coordsObj){
localStorage.setItem(COORDS, JSON.stringify(coordsObj));
}
function handleGeoSuccess(position){
// console.log(position);
const latitude = position.coord.latitude;
const longitude = position.coord.longitude;
const coordObj ={
latitude:latitude,
longitude:longitude
}
saveCoords(coordObj);
getWeather(coordObj.latitude, coordObj.longitude);
}
function handleGeoError(){
console.log("Cant access geo location");
const coordObj ={
latitude:37.475381899999995,
longitude:127.0430674
}
saveCoords(coordObj);
getWeather(coordObj.latitude, coordObj.longitude);
}
function askForCoords(){
navigator.geolocation.getCurrentPosition(handleGeoSuccess, handleGeoError);
}
function loadCoords(){
const loadedCoords = localStorage.getItem(COORDS);
if(loadedCoords === null){
console.log("none");
askForCoords();
}
else{
const parseCoords = JSON.parse(loadedCoords);
// console.log(parseCoords);
getWeather(parseCoords.latitude, parseCoords.longitude);
}
}
function init(){
loadCoords();
}
init();