const API_KEY = "ํค๊ฐ ๋ฃ์ผ์ฃผ๋ฉด๋จ ";
const WEATHER_API = "https://api.openweathermap.org/data/2.5/weather?";
const weather = document.querySelector(".js-weather .weather__text");
function getWeather(coords) {
fetch(
`${WEATHER_API}lat=${coords.lat}&lon=${
coords.lng
}&appid=${API_KEY}&units=metric`
)
.then(response => response.json())
.then(json => { // then์ ์ฌ์ฉํ ์ด์ ๋ fetch๊ฐ ์๋ฃ๋๊ธธ ๊ธฐ๋ค๋ ค์ผํ๊ธฐ๋๋ฌธ์ด๋ค.
const name = json.name;
const temperature = json.main.temp;
weather.innerHTML = `${Math.floor(temperature)}ยฐ @ ${name}`;
});
}
function handleGeoSuccess(position) {
const lat = position.coords.latitude;
const lng = position.coords.longitude;
const coords = {
lat, // key ์ value๊ฐ์ด ๊ฐ์ผ๋ฉด ์๋ต ๊ฐ๋ฅํ๋ค.
lng
};
localStorage.setItem("coords", JSON.stringify(coords));
getWeather(coords);
}
function handleGeoFailure() {
console.log("no location");
}
function loadWeather() {
const currentCoords = localStorage.getItem("coords");
if (currentCoords !== null) {
const parsedCoords = JSON.parse(currentCoords);
getWeather(parsedCoords);
return;
} else {
navigator.geolocation.getCurrentPosition(
handleGeoSuccess,
handleGeoFailure
);
}
}
function init() {
loadWeather();
}
init();