본문으로 바로가기

위치 정보 받아 날씨 제공

category 개발/JS 2020. 4. 1. 00:30

사용자의 위치 정보를 받아서 날씨를 안내한다. 유튜브 노마드 코더의 영상 (https://youtu.be/5fAMu2ORvDA) 을 정리했다. OpenWeather의 API를 이용하기 위해서는 가입해야 한다. https://openweathermap.org/ 홈페이지 방문해 가입한다. https://home.openweathermap.org/api_keys 에서 API 키를 확인해 JS 파일의 API_KEY 변수에 저장한다. 


<!DOCTYPE html>

<html>

  <head>

    <title>Something</title>

    <meta charset="utf-8" />

    <link rel="stylesheet" href="index.css" />

  </head>

  <body>

    <span class="js-weather"></span>

    <script src="weather.js"></script>

  </body>

</html>


const weather = document.querySelector(".js-weather");


const API_KEY = "12345678901234567891234567891234";

const COORDS = "coords";


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(json) {

    // console.log(json);

    const temperature = json.main.temp;

    const place = json.name;

    weather.innerText = `${temperature}°C @ ${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);

}


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 parseCoords = JSON.parse(loadedCoords);

    getWeather(parseCoords.latitude, parseCoords.longitude);

  }

}


function init() {

  loadCoords();

}


init();