본문 바로가기

TIL

TIL 23.07.14 오픈웨더맵 날씨 API 불러오기

완성본

현재 습도 99 % ... 

오늘은 오픈웨더맵을 이용해서 날씨 API 를 불러오는 방법에 대해 포스팅 하려고 한다. 다음주에 드디어 아웃소싱 프로젝트를 하는데 이게 외부 API 를 사용하는 것과 관련된다고 하길래 다시 복기하고자 함. 모자이크는 내가 사는 지역 이름임.

 

일단 오픈 웨더 맵을 들어가서 API 키를 얻어온다.

https://openweathermap.org/

 

Сurrent weather and forecast - OpenWeatherMap

Access current weather data for any location on Earth including over 200,000 cities! The data is frequently updated based on the global and local weather models, satellites, radars and a vast network of weather stations. how to obtain APIs (subscriptions w

openweathermap.org

 

회원가입하고 무료버전으로 키를 받아올 수 있음

Weather.jsx

 

현재 위치정보와 함께 다음처럼 불러오면 된다.

function Weather() {
  const [latitude, setLatitude] = useState(null);
  const [longitude, setLongitude] = useState(null);
  const [weatherData, setWeatherData] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    // 위치 정보 가져오기
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          setLatitude(position.coords.latitude);
          setLongitude(position.coords.longitude);
        },
        (error) => {
          setError("Unable to retrieve your location");
        }
      );
    } else {
      setError("Geolocation is not supported by your browser");
    }
  }, []);

  useEffect(() => {
    // 날씨 데이터 가져오기
    if (latitude && longitude) {
      const API_KEY = "나의 API_KEY";
      const API_URL = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`;

      fetch(API_URL)
        .then((response) => response.json())
        .then((data) => {
          setWeatherData(data);
        })
        .catch((error) => {
          setError("Unable to fetch weather data");
        });
    }
  }, [latitude, longitude]);

  if (error) {
    return <div>Error: {error}</div>;
  }

  if (!latitude || !longitude || !weatherData) {
    return <div>Loading...</div>;
  }

  const { name } = weatherData;
  const { temp, humidity } = weatherData.main;
  const { description } = weatherData.weather[0];

 

필요한 부분에 맞게 사용하면 됨.

참고로 temp 단위가 K 로 나오기때문에 C 로 고치려면 -273.15 를 해줘야함.. 300 도라 당황하지 않길 

  {Math.ceil(temp - 273.15)}°C

 

다음에는 카카오맵 API 에 도전해봐야겠다 🔥