const API_KEY = "3d12a474c2b6b29a679eb2b098bfe7d7";
const COORDS = "coords";
const weather = document.querySelector(".js-weather");
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 (jsonDifferent) {
console.log(jsonDifferent);
const temperature = jsonDifferent.main.temp;
const place = jsonDifferent.name;
weather.innerText = `현재 온도: ${temperature}도
현재 위치: ${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("Cant Access geo location");
}
function askForCoords() {
navigator.geolocation.getCurrentPosition(handleGeoSuccess, handleGeoError);
}
function loadCoords() {
const loadedCoords = localStorage.getItem(COORDS);
if (loadedCoords === null) {
askForCoords();
} else {
const parsedCoords = JSON.parse(loadedCoords);
getWeather(parsedCoords.latitude, parsedCoords.longitude);
}
}
function init() {
loadCoords();
}
init();