[JS ES6] OpenWeather API 활용하기

choii_ii·2025년 3월 26일

[JS ES6] 스터디노트

목록 보기
5/6

위치+날씨 API 활용하기

📌 KEY POINT

💚 navigator.geolocation.getCurrentPosition() : 현재 위치(위도, 경도)를 가져오기
💚 OpenWeather API를 통해 해당 위치의 날씨 정보를 가져오기


👉🏻 마크업은 이렇게! (HTML5)

🩵 온도와 지역위치를 노출시킬 요소 생성
🔹 자세한 데이터 값은 weather API를 통해 불러올 것!

<body>
    <div id="weather">
        <span></span>
        <span></span>
    </div>
</body>

👉🏻 스크립트는 이렇게! (JS ES6)

🩵 navigator.geolocation.getCurrentPosition(성공 함수, 실패 함수)
🔹 브라우저에서 제공하는 위치 정보를 가져오는 메서드
🔹 position.coords.latitude : 위도
🔹 position.coords.longitude : 경도

🩵 onGeoOk(position) 함수 설명 : 위치를 성공적으로 가져오면 해당 함수 실행
🔹 position은 위치 정보를 담고 있는 객체
🔹 사용자의 위도(latitude), 경도(longitude) 등 위치 관련 정보를 불러와 변수에 저장
🔹 OpenWeather API를 사용하기 위한 API 키 값을 가져와 변수에 저장
🔹 OpenWeather API의 날씨 정보 요청 URL을 만듦
🔹 lat={lat}&lon={lng} : 사용자 위치(위도, 경도)를 기반으로 날씨 데이터 요청
🔹 appid=${API_KEY} : API 키 추가
🔹 units=metric : 섭씨 온도로 데이터 요청
🔹 fetch(url) : 해당 URL로 API 요청을 보냄 (실제로 URL 이동할 필요 없이 스크립트가 대신 URL을 부름)
🔹 API 요청에 따른 데이터를 받으면, .name (지역명)과 .main.temp (온도) 값을 출력하여 text요소로서 HTML에 반환

🩵 onGeoError() 함수 설명 : 위치 가져오는 것을 실패했을 때, 해당 함수 실행

<script>
// navigator.geolocation.getCurrentPosition(성공 함수, 실패 함수);

const API_KEY = "OpenWeather에서 부여받은 API 키 값";

// 성공 함수
function onGeoOk(position){
    // console.log(position);
    
    const lat = position.coords.latitude; // 위도
    const lng = position.coords.longitude; // 경도
    
    const url = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lng}&appid=${API_KEY}&units=metric`;
    
    fetch(url)
    .then(function(response){
        return response.json()
    })
    .then(function(data){
        const weather = document.querySelector("#weather span:first-child");
        const city = document.querySelector("#weather span:last-child");

        city.innerText = data.name;
        weather.innerText =  `${Math.round(data.main.temp)} / ${data.weather[0].main}`;

    }); 
}

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

navigator.geolocation.getCurrentPosition(onGeoOk, onGeoError);
</script>

이렇게 API를 통해 위치와 날씨 정보를 가져오면 아래와 같이 데이터 값이 노출된다.

위치+날씨 API 활용하기


📌 fetch란?

💚 fetch는 브라우저에서 기본 제공하는 메서드로, 웹 서버와 비동기적으로 데이터를 주고받기 위해 사용된다.
🔸 비동기란? : 데이터를 요청한 후, 결과를 기다리지 않고 다른 작업을 먼저 처리할 수 있다는 의미이며,이를 통해 사용자 경험이 더 부드럽고, 앱이 더 빠르게 동작할 수 있다.

💚 fetch 기본 문법
🔹 url: 데이터를 요청할 서버의 URL
🔹 options: 요청을 더 구체적으로 설정할 수 있는 선택 사항 (예: HTTP 메서드, 헤더 등)

fetch(url, [options])
  .then(response => response.json())  // 응답 처리
  .then(data => console.log(data))    // 실제 데이터 처리
  .catch(error => console.log(error)); // 오류 처리

✅ fetch() 동작 방식

1️⃣ fetch(url): URL로 요청을 보냄. 이때 fetch()는 데이터를 바로 반환하지 않고, "나중에 결과를 줄게!"라는 약속(Promise)을 먼저 반환한다. 그래서 데이터를 비동기적으로 처리할 수 있는 것!

2️⃣ response.json() : 응답이 JSON 형식이라면, JSON 형태로 파싱해서 반환

3️⃣ then(data) : 요청이 성공적으로 완료되면 응답(response)이 then(data)을 통해 실제 데이터를 처리!

4️⃣ catch(error) : 오류가 발생했을 때, 오류를 처리하는 부분. 예를 들어, 서버 연결이 안 됐거나, 잘못된 URL을 요청했을 때 실행된다.

profile
퍼블리셔 / 작업 기로끄v

0개의 댓글