Getting the Weather part One Geolocation

Getting the Weather part One Geolocation

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();

API

API๋Š” ํŠน์ • ์›น์‚ฌ์ดํŠธ๋กœ๋ถ€ํ„ฐ ๋ฐ์ดํ„ฐ๋ฅผ ์–ป๊ฑฐ๋‚˜ ์ปดํ“จํ„ฐ๋ผ๋ฆฌ ์†Œํ†ตํ•˜๊ธฐ ์œ„ํ•ด ๊ณ ์•ˆ๋œ๊ฒƒ์ด๋‹ค.

Last updated