-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweather.js
48 lines (40 loc) · 1.12 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
const COORDS = "coords";
//https://openweathermap.org/
const apiKey = "8f36b65af0bd7bd836f44329dd94d168";
function getWeather(latitude, longitude){
fetch(
`https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${apiKey}&units=metric`
).then((response) => {
return response.json();
}).then((json) => {
console.log(json);
})
}
function saveCoords(coordsObj){
localStorage.setItem(COORDS, JSON.stringify(coordsObj));
}
function success(position){
console.log(position);
const coordsObj = {
latitude : position.coords.latitude,
longitude : position.coords.longitude
};
saveCoords(coordsObj);
}
function error(error){
console.error(error);
}
function askCoords(){
console.log(navigator.geolocation);
navigator.geolocation.getCurrentPosition(success, error);
}
function init(){
const coords = localStorage.getItem(COORDS);
if(coords === null){
askCoords();
}else{
const coordOBJ = JSON.parse(localStorage.getItem(COORDS));
getWeather(coordOBJ.latitude, coordOBJ.longitude);
}
}
init();