inblog logo
|
vosw1
    Script

    바닐라 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
    GeolocationPosition - Web API | MDN
    GeolocationPosition 인터페이스는 주어진 시간에 장치가 위치한 지점을 나타냅니다. 지점은 Coordinates 객체로 표현하여, 지구를 나타내는 회전타원체 위의 2D 위치와 더불어 높이와 속도 정보를 담습니다.
    GeolocationPosition - Web API | MDN
    https://developer.mozilla.org/ko/docs/Web/API/GeolocationPosition
    GeolocationPosition - Web API | MDN
    • 위치 기반 서비스를 제공
    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. 내 위치에 해당하는 날씨 찾기

    • 사이트에 들어가서 로그인하기 (계정이 없으면 만들어서 로그인하기)
      • Weather API
        Explore OpenWeather's vast range of weather APIs including the versatile One Call API 3.0. Ideal for both beginners and professionals, our APIs offer current weather, minute-by-minute forecasts, historical data archives, and future predictions. Access up to 45 years of weather data, global weather maps, solar irradiance predictions, air pollution data, and more. Our APIs support various formats like JSON, XML, and are ideal for middle-sized projects to enterprise-level solutions.
        Weather API
        https://openweathermap.org/api
    • 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

    vosw1

    RSS·Powered by Inblog