React OpenWeatherMap api 사용하기

2021. 6. 8. 10:10React

https://openweathermap.org/api

 

Weather API - OpenWeatherMap

Please, sign up to use our fast and easy-to-work weather APIs for free. In case your requirements go beyond our freemium account conditions, you may check the entire list of our subscription plans. You can read the How to Start guide and enjoy using our po

openweathermap.org

위 주소로 이동 후 회원가입을 진행하시면 개인 api키가 발급됩니다.

 

api 키

 

 

OpenWeatherMap api는 완전 무료는 아니고 부분 무료 입니다.

사용방법은 간단합니다.

1. 회원가입

2. api키 발급

3. 발급받은 api키 사용

  const [coords, saveCoords] = useState();
  const [temp, setTemp] = useState();
  const [weather, setWeather] = useState();
    
   function handleGeoSucc(position) {
    console.log(position);
    const latitude = position.coords.latitude;  // 경도  
    const longitude = position.coords.longitude;  // 위도
    const coordsObj = {
      latitude,
      longitude
    }
    saveCoords(coordsObj);
    getWeather(latitude, longitude);
  }

  function handleGeoErr(err) {
    console.log("geo err! " + err);
  }

  function requestCoords() {
    navigator.geolocation.getCurrentPosition(handleGeoSucc, handleGeoErr);
  }

  function getWeather(lat, lon) {
    fetch(`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${'발급받은 api키'}&units=metric`)
      .then(res => res.json())
      .then(data => {
        console.log(data);
        const temp = data.main.temp;
        const weathers = data.weather[data.weather.length - 1];
        setTemp(temp);
        setWeather(weathers.main);
      })
  }

  useEffect(() => {
    requestCoords();
  }, []);

 

위와 같이 코드를 작성하고 json형태로 넘어온 data를 콘솔로 찍어보면 아래와 같이 출력됩니다.

 

json 형태로 넘어온 data 정보

아래와 같이 필요한 데이터만 추출해 사용할 수 있습니다.

 

 

'React' 카테고리의 다른 글

Code Splitting 과 React lazy, Suspense  (0) 2021.06.23
[React] useSelector, useDispatch  (0) 2021.06.23
useCallback 컴포넌트 성능 최적화  (0) 2021.06.03
react class형, function형 차이  (0) 2021.06.03
react map  (0) 2021.06.03