개발공부/JavaScript 강의

[노마드코더] 바닐라 JS로 크롬 앱 만들기 #07 (weather)

김놀먹 2021. 11. 10. 14:23

getCurrentPosition() : 장치의 현재 위치를 가져옴

openwhathermap 사이트 : https://openweathermap.org/

 

Сurrent weather and forecast - OpenWeatherMap

Access current weather data for any location on Earth including over 200,000 cities! The data is frequently updated based on the global and local weather models, satellites, radars and a vast network of weather stations. how to obtain APIs (subscriptions w

openweathermap.org

fetch : 서버에 네트워크 요청을 보내고 새로운 정보를 받아옴

 

const API_KEY = "본인의 API_KEY"

function onGeoOK(position) {
  const lat = position.coords.latitude;
  const lon = position.coords.longitude;
  const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=metric`
  fetch(url)
    .then(Response => Response.json())
    .then(data => {
      const weather = document.querySelector("#weather span:first-child")
      const city = document.querySelector("#weather span:last-child")
      city.innerText = data.name;
      weather.innerText = data.weather[0].main
      });
}
function onGeoError(){
  alert("Can't find you. No whather for you.");
}


navigator.geolocation.getCurrentPosition(onGeoOK, onGeoError);