Study/JavaScript

[JS] 기상청 날씨 API를 이용해 현재 날씨 받아오기

taecongs 2024. 1. 11. 13:26

알고있으면 좋은 Javascript Tip✨


기상청 날씨 API를 이용해 현재 날씨 받아오기

 

(1) 활용 신청 진행하기

  • 사용 할 API의 활용 신청을 진행하면 서비스 키를 발급 받아 사용할 수 있다.

 

(2) 적용 전 테스트 진행하기

  • Service Key를 발급 받았다면 테스트를 먼저 진행해 본 뒤 코드에 적용하면 더욱 좋다.
  • 요청변수를 작성하고 미리보기를 클릭하면 받아오는 데이터를 확인해 볼 수 있다.
  • 좌표 값은 기상청에서 제공하는 기상청41_단기예보 조회서비스_오픈API활용가이드_최종 파일을 다운 받아서 적용해주면 된다. (xlsx 파일) 

 

(3) API 호출하기

    const apiKey = "발급받은 API 인증키";
    const numOfRows = 12;  // 한 페이지 결과 수
    const currentDay = setToday();  // 현재 날짜
    const currentTime = setToday(); // 현재 시간
    const nx = 69;    // x 좌표
    const ny = 133;   // y 좌표

    const api = `https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getVilageFcst?serviceKey=${apiKey}&pageNo=1&numOfRows=${numOfRows}&dataType=JSON&base_date=${currentDay.formattedDate}&base_time=${currentTime.formattedTime}&nx=${nx}&ny=${ny}`;

    fetch(api)
        .then(response => response.json())
        .then(data => {
            setWeather(data);
        })
        .catch(error => {
            console.log(error);
        });
}

 

(4) 코드 적용하기

function setWeather(data: { response: { body: { items: { item: any[] } } } }) {
  const currentWeatherIcon: HTMLImageElement | null = document.querySelector("#weather-value");
  const currentTemperature: HTMLSpanElement | null = document.querySelector("#temper-value");
  const currentPrecipitation: HTMLSpanElement | null = document.querySelector("#precip");
  const currentHumidity: HTMLSpanElement | null = document.querySelector("#humidity");
  const currentWindDirection: HTMLSpanElement | null = document.querySelector("#wind-direction");
  const currentWindSpeed: HTMLSpanElement | null = document.querySelector("#wind-speed");

  // 현재 시간 정의
  const today: Date = new Date();
  const isCurrentTime = today.getHours();
  let hourStr: string = isCurrentTime < 10 ? "0" + isCurrentTime : String(isCurrentTime);


  // 현재 온도 정의
  if (currentTemperature) {
    currentTemperature.innerText =
      data.response.body.items.item[0].fcstValue.toString();
  }

  // 강수확률 정의
  if (currentPrecipitation) {
    currentPrecipitation.innerText =
      data.response.body.items.item[7].fcstValue.toString() + "%";
  }

  // 습도 정의
  if (currentHumidity) {
    currentHumidity.innerText =
      data.response.body.items.item[10].fcstValue.toString() + "%";
  }

  // 풍향,풍속 정의
  if (currentWindDirection && currentWindSpeed) {
    const deg = data.response.body.items.item[3].fcstValue;

    const convertDirection = (deg: number): string => {
      const directions = [
        "북",
        "북북동",
        "북동",
        "동북동",
        "동",
        "동남동",
        "남동",
        "남남동",
        "남",
        "남남서",
        "남서",
        "서남서",
        "서",
        "서북서",
        "북서",
        "북북서",
        "북",
      ];

      const convertedValue = Math.round((deg + 22.5 * 0.5) / 22.5);
      return directions[convertedValue % 16];
    };

    const windDirectionText = convertDirection(deg);
    currentWindDirection.innerText = windDirectionText + "풍";

    currentWindSpeed.innerText =
      data.response.body.items.item[4].fcstValue.toString() + "m/s";
  }
}

'Study > JavaScript' 카테고리의 다른 글

[JS] AJAX  (0) 2024.01.18
[JS] fetch (원격 API 호출)  (0) 2024.01.10
[JS] Axios  (0) 2024.01.10
[JS] every & some  (0) 2023.12.26
[JS] startsWith & endsWith  (0) 2023.12.22