본문 바로가기
ReactNative

날씨정보 가져오기 Weather API

by 피이웅콱푸지이삐용삐용지요지용뿌에에콱 2022. 8. 6.

서버가 제공하는 도메인 형식의 API를 사용하려면, 사용을 위한 도구가 필요합니다. 이를 axios 라고 부릅니다.

yarn add axios

axios 설치

import axios from "axios"

axios 임포트

 const getLocation = async () => {
    //수많은 로직중에 에러가 발생하면
    //해당 에러를 포착하여 로직을 멈추고,에러를 해결하기 위한 catch 영역 로직이 실행
    try {
      //자바스크립트 함수의 실행순서를 고정하기 위해 쓰는 async,await
      await Location.requestForegroundPermissionsAsync();
      const locationData= await Location.getCurrentPositionAsync();
      console.log(locationData)
      console.log(locationData['coords']['latitude'])
      console.log(locationData['coords']['longitude'])
      const latitude = locationData['coords']['latitude']
      const longitude = locationData['coords']['longitude']
      const API_KEY = "WeatherAPI KEY";
      const result = await axios.get(
        `http://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}&units=metric`
      );

      console.log(result)

    } catch (error) {
      //혹시나 위치를 못가져올 경우를 대비해서, 안내를 준비합니다
      Alert.alert("위치를 찾을 수가 없습니다.", "앱을 껏다 켜볼까요?");
    }
  }

위도,경도, api키값을 파람값으로 넣어 데이터를 가져온다.

 

API키값은 Weather API사이트에서 회원가입후 받을수있다.

 

Weather API 공식문서

 

Weather API - OpenWeatherMap

Please, sign up to use our fast and easy-to-work weather APIs. As a start to use OpenWeather products, we recommend our One Call API 3.0. For more functionality, please consider our products, which are included in professional collections.

openweathermap.org