보라코딩

자바스크립트로 날씨 본문

코딩/HTML5, CSS3, JS

자바스크립트로 날씨

new 보라 2023. 9. 19. 12:49
코드가 엄청 심플해서 놀랐다!
유용한 코드라 생각해서 기록하기 :)
 
 
 
날씨 API는 아래 사이트 참고하기!
 

Weather API - OpenWeatherMap

Please, sign up to use our fast and easy-to-work weather APIs. As a start to use OpenWeather products, we recommend our One Call API 3.0. For more functionality, please consider our products, which are included in professional collections.

openweathermap.org

 

 

 
 
weather.js
 
 
const API_KEY = "키를 넣으시오~~~";

function onGeoSuccess(position) {
  const lat = position.coords.latitude;
  const lng = position.coords.longitude;

  console.log("너 여기 살아!", lat, lng);

  const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lng}&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} / ${data.main.temp}`;
    });
}

function onGeoError() {
  alert("Can't find you. No weather for you.");
}

console.log(navigator.geolocation.getCurrentPosition(onGeoSuccess, onGeoError));