[날씨 API] OpenWeatherMap

조아영·2024년 7월 16일

◼ API key 받는 법

  1. https://openweathermap.org/에 회원가입합니다.
  2. 로그인 후 오른쪽 상단 "사용자이름"을 클릭합니다.
  3. "My API keys"버튼을 선택합니다.
  4. "API keys"탭에서 나의 API key를 확인합니다.

◼ 예제

html

<html>
    <body>
        <button class="button">버튼</button>
        <div>위치 : <span class="weather-location"></span></div>
        <div>기온 : <span class="weather-temperature"></span></div>
        <div>날씨 : <span class="weather-description"></span><img class="weather-icon" /></div>
    </body>
</html>

javascript

const button = document.querySelector(".button");

button.addEventListener("click", () => {
    const API_KEY = "API_KEY값";
    const weatherLocation = document.querySelector(".weather-location");
    const weatherTemperature = document.querySelector(".weather-temperature");
    const weatherDescription = document.querySelector(".weather-description");
    const weatherIcon = document.querySelector(".weather-icon");

    const success = (position) => {
        // latitude = 위도, longitude = 경도
        const latitude = position.coords.latitude;
        const longitude = position.coords.longitude;

        getWeather(latitude, longitude);
    };

    // 사용자가 현재 위치 엑세스 허용하지 않은 경우 fail()
    const fail = () => {
        alert("위치 권한이 거부 되었습니다.");
    };
	
  	// 버튼 클릭 시 현재 위치 정보 받기
    // navigator.geolocation.getCurrentPosition()로 position정보 받기
    navigator.geolocation.getCurrentPosition(success, fail);

    const getWeather = (lat, lon) => {
        // fetch()로 API 호출
        fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=metric&lang=kr`)
            // json으로 변환
            .then((response) => {
                return response.json();
            })
            // json 데이터 가져오기
            .then((json) => {
                console.log(json);

                const location = json.name;
                const temperature = json.main.temp;
                const description = json.weather[0].description;
                const icon = json.weather[0].icon;
                const iconURL = `http://openweathermap.org/img/wn/${icon}@2x.png`;

                weatherLocation.innerText = name;
                weatherTemperature.innerText = temperature;
                weatherDescription.innerText = description;
                weatherIcon.setAttribute("src", iconURL);
            })
            // 에러처리
            .catch((error) => {
                alert(error);
            });
    };
});

0개의 댓글