바닐라 JS) 19. 내 위치의 날씨 만들기

송민경's avatar
Sep 03, 2024
바닐라 JS) 19. 내 위치의 날씨 만들기

1. weather.js 만들기

  • index.html에 연결하기
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="css/style.css"> </head> <body> <form class="login-form hidden" id="login-form"> <input required maxlength="15" type="text" placeholder="What is your name?" /> </form> <h2 id="clock">00:00:00</h2> <h1 class="hidden" id="greeting" ></h1> <form id="todo-form"> <input type="text" placeholder=" 할일을 쓰고 enter를 누르세요" required/> </form> <ul id="todo-list"></ul> <div id="quote"> <span></span> <span></span> </div> <script src="js/greetings.js"></script> <script src="js/clock.js"></script> <script src="js/quotes.js"></script> <script src="js/background.js"></script> <script src="js/todo.js"></script> <script src="js/weather.js"></script> </body> </html>
 

2. 내 위치 찾기

  • Geolocation API
  • 위치 기반 서비스를 제공
navigator.geolocation.getCurrentPosition() // 사용자의 현재 위치(위도와 경도)를 가져오기
  • getCurrentPosition 함수는 두 개의 콜백 함수가 인자로 필요함
    • 성공 시 실행되는 콜백 함수: 위치 정보를 성공적으로 가져왔을 때 호출
    • 실패 시 실행되는 콜백 함수: 위치 정보를 가져오는 데 실패했을 때 호출
    • navigator.geolocation.getCurrentPosition( function(position) { // 성공적으로 위치 정보를 받아온 경우 실행 const latitude = position.coords.latitude; // 위도 const longitude = position.coords.longitude; // 경도 console.log(`위도: ${latitude}, 경도: ${longitude}`); }, function(error) { // 위치 정보를 받아오는 데 실패한 경우 실행 console.error("위치 정보를 가져오지 못했습니다.", error); } );
      notion image
      notion image
      function onGeoOk(position){ console.log(position); } function onGeoError(){ alert("위치를 찾을 수 없어요. 날씨를 찾을 수 없어요ㅜ") } navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);
      notion image
      notion image
      function onGeoOk(position){ const lat = position.coords.latitude; const lng = position.coords.longitude; console.log(`당신은 ${lat} ${lng} 있어요~`); } function onGeoError(){ alert("위치를 찾을 수 없어요. 날씨를 찾을 수 없어요ㅜ") } navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);
      notion image
 

3. 내 위치에 해당하는 날씨 찾기

  • API 키 만들기
    • notion image
      notion image
  • 문서에서 URL 확인하기
    • notion image
      https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={API key}
  • 실제 위치와 API 키 입력해서 확인하기
    • https://api.openweathermap.org/data/2.5/weather?lat=35.1535104&lon=129.024&appid=46c42ba74d2d22c044c652e13464ef9b
      notion image
  • API_KEY와 URL 변수 추가하기
    • weather.js
    • const API_KEY = "46c42ba74d2d22c044c652e13464ef9b"; function onGeoOk(position){ const lat = position.coords.latitude; const lon = position.coords.longitude; console.log(`당신은 ${lat} ${lon}에 있어요~`); const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}`; console.log(url); } function onGeoError(){ alert("위치를 찾을 수 없어요. 날씨를 찾을 수 없어요ㅜ") } navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);
      notion image
      notion image
  • fetch 이용하기
  • URL 얻기
    • const API_KEY = "46c42ba74d2d22c044c652e13464ef9b"; 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}`; fetch(url); // url에 갈 필요없이 JS가 대신 호출 } function onGeoError(){ alert("위치를 찾을 수 없어요. 날씨를 찾을 수 없어요ㅜ") } navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);
notion image
notion image
notion image
  • 섭씨로 바꾸기
    •  units : 온도 측정 단위를 설정
      • standard (기본값) : 켈빈(K) 단위로 표시
      • metric : 섭씨(°C) 단위로 표시
      • imperial : 화씨(°F) 단위로 표시
      https://api.openweathermap.org/data/2.5/weather?lat=35.1535104&lon=129.024&appid=46c42ba74d2d22c044c652e13464ef9b&units=metric
      notion image
    • weather.js의 url에도 추가
    • const API_KEY = "46c42ba74d2d22c044c652e13464ef9b"; 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); // url에 갈 필요없이 JS가 대신 호출 } function onGeoError(){ alert("위치를 찾을 수 없어요. 날씨를 찾을 수 없어요ㅜ") } navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);
const API_KEY = "46c42ba74d2d22c044c652e13464ef9b"; 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 =>{ console.log(data.name, data.weather[0].main); }); } function onGeoError(){ alert("위치를 찾을 수 없어요. 날씨를 찾을 수 없어요ㅜ"); } navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);
notion image
  • 화면에 날씨와 지역 표시하기
    • index.html
    • <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="css/style.css"> </head> <body> <form class="login-form hidden" id="login-form"> <input required maxlength="15" type="text" placeholder="What is your name?" /> </form> <h2 id="clock">00:00:00</h2> <h1 class="hidden" id="greeting" ></h1> <form id="todo-form"> <input type="text" placeholder=" 할일을 쓰고 enter를 누르세요" required/> </form> <ul id="todo-list"></ul> <div id="quote"> <span></span> <span></span> </div> <div id="weather"> <span></span> <span></span> </div> <script src="js/greetings.js"></script> <script src="js/clock.js"></script> <script src="js/quotes.js"></script> <script src="js/background.js"></script> <script src="js/todo.js"></script> <script src="js/weather.js"></script> </body> </html>
    • weather.js
    • const API_KEY = "46c42ba74d2d22c044c652e13464ef9b"; 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("위치를 찾을 수 없어요. 날씨를 찾을 수 없어요ㅜ"); } navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);
      notion image
  • 온도 추가하기
    • weather.js
    • const API_KEY = "46c42ba74d2d22c044c652e13464ef9b"; 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} / ${data.main.temp}`; }); } function onGeoError(){ alert("위치를 찾을 수 없어요. 날씨를 찾을 수 없어요ㅜ"); } navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);
      notion image
Share article
RSSPowered by inblog