본문 바로가기
개발활용툴

날씨 API - OpenWeather 사용하기(2)

by 즐거운코딩 2023. 12. 14.
반응형

2023.12.13 - [개발활용툴] - 날씨 API - OpenWeather 사용하기(1)

 

날씨 API - OpenWeather 사용하기(1)

날씨 정보는 다양한 종류에 활용도가 높은 컨텐츠 중에 하나입니다. 본인이 제공하는 주요 컨텐츠에 맞게 적절하게 사용한다면 좀 더 풍부한 정보를 가진 사이트를 만들 수 있겠습니다. 여러 종

peter-codinglife.tistory.com

이전 블로그에 이어서 실제 OpenWeather API 사용 예시입니다.

 

예시는 아래와 같이 경복궁 소개 상세페이지입니다. 

기본정보 이외 지도에 위치정보를 보여주고, 현재 날씨 정보를 보여줍니다.

날씨정보 표출 내용은 날씨 아이콘, 온도, 기준 시간 입니다. 

 

show.ejs 파일 - 지도 및 날씨 정보 표출 하기

  <div class="col-6">
    <div id="map" class="mb-3"></div>
    <div class="mb-3">
      <img src="<%=iconUrl %>" alt="" />
      <div>
        <span><%= weatherType %></span
        ><span class="ms-2"><%= currTemp %>℃</span>
      </div>
      <small class="text-body-secondary"><%=currTime %></small>
      <!-- <img src="/icons/cloudy_sun_icon.png" alt="" /> 아이콘 이미지 사용-->
    </div>
</div>

 

controller.js 파일 - OpenWeather API 를 불어와서 날씨 정보 show.ejs 로 전달

  // openweather api 통해서 관광지위치의 현재 날씨정보 불러오기, units ℃ 표시
  const response = await fetch(
    `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${openWeatherToken}&lang=kr&units=metric`
  );
  const data = await response.json();
  const currTemp = Math.round(data.main.temp * 10) / 10;
  const weatherType = data.weather[0].description;
  const currTime = getYmd10(data.dt);
  const iconUrl = `https://openweathermap.org/img/wn/${data.weather[0].icon}@2x.png`;
  console.log("weather:", data);
  console.log("temp:", currTemp);
  console.log("날씨:", weatherType);
  console.log("기준시간:", getYmd10(data.dt));
  console.log("아이콘", iconUrl);

  if (!campground) {
    req.flash("error", "데이터를 찾을 수 없습니다.");
    return res.redirect("/campgrounds");
  }
  res.render("campgrounds/show", {
    campground,
    imageList,
    weatherType,
    currTemp,
    currTime,
    iconUrl,
    getYmd10,
  }); // 날짜 포맷 변경위해 함수 같이 넘김
};

 

  • fetch 로 좌표기반의 현재 날씨 조회 API 를 호출하여 데이터를 수신하고,
  • 온도는 소숫점 1자리로 반올림하고,
  • 날씨 타입으로 상태값을 가져오고,
  • 현재시간은 UTC 시간을 한국날짜 및 시간으로 변경하고 (getYmd10 함수 만들어서 사용)
  • 날씨 타입 아이콘은 icon id 를 호출하여 가져옴
  • res.render 로 표출할 정보를 show.ejs 로 보냄

 기본적인 사용예시로 현재 시간 , 지도상 위치의 날씨를 표출해 보았습니다.

반응형