코딩/API

날씨 가져오기 Openweather

춘 몽 2024. 3. 31. 22:56
728x90

https://openweathermap.org/

 

Сurrent weather and forecast - OpenWeatherMap

OpenWeather Weather forecasts, nowcasts and history in a fast and elegant way

openweathermap.org

가입 하고 API키를 받는다.

 

API탭에 원하는 기능별 API doc이 있는데, 보통 현재 날씨데이터를 요청하므로 Current Weather Data의 API doc의 링크를 남긴다.

https://openweathermap.org/current

 

Current weather data - OpenWeatherMap

 

openweathermap.org

 

보면 API call에 요청하는 주소와 내용이 나와있다.

쉽게 API 처리하기 위해 axios를 설치한다.

yarn add axios

 

import axios from "axios";

export const getWeather = async ({ latitude, longitude }) => {
  const weatherAPIKEY = process.env.REACT_APP_WEATHER_API_KEY;
  const weaherURL = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${weatherAPIKEY}&units=metric&lang=kr`;

  try {
    const res = await axios.get(weaherURL);
    return res;
  } catch (err) {
    console.error(err);
    alert("날씨 데이터를 가져오는데 실패했습니다.");
  }
};

내가 사용한 방법이다.

다른곳에서 사용하기 위해 export 했고, async await처리를 해두었다.

api 추가적으로 units와 lang를 추가했는데,

온도가 화씨( °F)로 와서 units를 통해 섭씨(°C)로 바꿔주었고,

한국어로 데이터를 준다고 해서 lang을 추가했는데, description만 한글로 오고 그것도 별로 와닿지 않는 한글? 이 온다.

 

lat와 lon은 앞서 작성한 geolocation을 사용하면 쉽게 가져올 수 있다.

https://springdream0406.tistory.com/74

 

위치 정보 가져오기 Geolocation

const geolocation = () => { navigator.geolocation.getCurrentPosition( (성공) => 성공, (실패) => 실패 ); }; 예시 코드를 이러며, 성공에는 latitude와 longtitude가 담겨있고, 실패에는 error의 code와 설명인 message가 담겨온

springdream0406.tistory.com

 

만약 위경도가 아닌 도시이름으로 검색하려면 위에 있는 API doc의 하단쯤에 예시코드가 있다.

앞서 말했던것처럼 기본 예시 API에 추가기능들을 넣고 할 수 있으니 사용전에 doc을 한번 훑어보는걸 추천한다.

 

 

++ 리턴받는 도시들 이름 길이 체크할 일이 생겨서 찾아보니  OpenWeather에서 제공하는 파일이 있길래 첨부한다.

cities_list.xlsx
0.02MB

 

참고로 아래 링크를 통해 받음.

https://openweathermap.org/storage/app/media/cities_list.xlsx

 

728x90