-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweather.js
57 lines (48 loc) · 1.46 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
const weather = document.querySelector(".js-weather");
const API_KEYS = "34d747d27b47c269be65453245db28d1";
const COORDS = "coords";
function getWeather(latitude, longitude){
fetch(
`https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEYS}&units=metric`
).then(function(weatherData){
weatherData = weatherData.json();
return weatherData;
}).then(function(data){
const temperature = data.main.temp;
const location = data.name;
console.log(temperature, location);
weather.innerText = `${temperature} at ${location}`;
});
};
function saveCoords(posObj){
localStorage.setItem(COORDS, JSON.stringify(posObj));
};
function handlePosSuccess(position){
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
const posObj = {
latitude,
longitude
}
saveCoords(posObj);
getWeather(latitude, longitude);
};
function handlePosFail(){
console.log("Can't access Position");
};
function askForCoords(){
navigator.geolocation.getCurrentPosition(handlePosSuccess, handlePosFail);
};
function loadCoords(){
const loadedCoords = localStorage.getItem(COORDS);
if(loadedCoords === null){
askForCoords();
} else {
const parseCoords = JSON.parse(loadedCoords);
getWeather(parseCoords.latitude, parseCoords.longitude);
}
};
function init(){
loadCoords();
};
init();