ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [React Native] 날씨 및 대기오염 API 로 데이터 가져오기
    React.js 2020. 4. 30. 21:50

     

    디바이스의 현재 위치를 위도, 경도로 가져왔으니 해당 위치의 날씨 및 대기오염 정보를 API 를 통해서 가져와보자. 

    디바이스의 현재 위치를 가져오는 법은 아래의 이전 게시글을 참고.

    [React Native] 디바이스의 현재 위치 가져오기

     

    [React Native] 디바이스의 현재 위치 가져오기

    React Native 의 개발환경을 세팅하고 Expo 에 대한 설명은 아래를 참고! [React Native] Hello World! 개발환경 세팅하기 [React Native] Hello World! 개발환경 세팅하기 React Native 를 시작하게 된 계기 일전..

    e-hyun.tistory.com

     

     

    적합한 API 찾기 : AirVisual

    날씨 및 대기오염 정보를 가져오기 위해서 나는 AirVisual Open API 를 활용할 예정이다. 

    AirVisual 말고도 이것저것 여기저기 찾아보면 위도/경도가 아니어도 지역, KM 좌표 (뭔지 모름, 좌표를 표시하는 법이 다양한 것 같다.), 관측소 위치 등등으로 데이터를 가져올 수 있는 API 들이 많다. API 를 찾을 때 생각했던 Spec 과 일치하는 API 로 찾아야 하는데, 나 같은 경우는 위도/경도로 데이터를 가져올 수 있으면서도, Global 을 대상으로 하고 있는 API 가 필요했다. 

    https://www.iqair.com/air-pollution-data-api

     

    AirVisual API | Trusted Live and Forecast Air Pollution Data

    Enhance your projects with free trusted historical, real-time and forecast air quality data. Air pollution and weather data for more than 60 countries worldwide.

    www.iqair.com

     

    위의 사이트로 들어가서 가입을 하고 Available Plans 를 보면 세가지 타입이 있는데, Community 말고는 모두 유료이다. 차이점은 한 달동안 API 호출 횟수가 다르고, API 의 Return 값으로 나타나는 정보들이 유료로 갈수록 더 자세하다는 것. 

    나는 무료 버전도 상관이 없었기때문에 (사실 미세먼지의 값을 가져오기 위해서는 Startup 버전으로 신청을 해야했지만, 유료이므로 깔끔하게 포기 ㅎㅎ) 무료버전으로 API 를 신청하였다. API 를 신청하면 사용할 수 있는 Key 를 발급받는다. 

     

     

     

    AirVisual API Spec 살펴보기

    그렇다면 본격적으로 사용할 API 의 Spec 을 살펴보자. Docs 로 고고.

    https://api-docs.airvisual.com/?version=latest#intro

    여러가지 API 를 사용할 수 있는 것을 볼 수 있는데, 내가 사용할 것은 위도/경도로 데이터를 받는 것이므로 Get nearest city data (GPS coordinates) 를 사용하면 되겠다. 

    api.airvisual.com/v2/nearest_city?lat={{LATITUDE}}&lon={{LONGITUDE}}&key={{YOUR_API_KEY}}

    url Param 으로 세가지 데이터만 보내주면 된다. 굿굿

    Return 값을 보면 데이터가 엄청 많은 것을 볼 수 있는데, Community Plan 인 경우에는 이 모든 데이터를 다 주진 않고, 일부 데이터만 준다. Return 값의 명세는 https://api-docs.airvisual.com/?version=latest#detailed-response-example 여기를 참고할 것.

     

     

    Get nearest city data (GPS Coordinates) API 호출하기

    API 에서 데이터를 Fetch 하기 위해서 Axios 를 사용할 예정이다.

    npm install axios

    요렇게 axios 를 프로젝트에 설치하고, 

    import axios from "axios";

    요렇게 axios 를 import 를 하면 사용할 준비는 완료.

    이제 API 로 데이터를 가져올 함수를 만들어보자. 

    getWeather = async(latitude, longitude) => {
        const { data } = await axios.get(
        `http://api.airvisual.com/v2/nearest_city?lat=${latitude}&lon=${longitude}&key=${API_KEY}`
        );
        console.log(data);
      }

    getWeather 함수는 위도/경도를 받아서 API 를 호출하고 리턴값을 data 에 넣는다. 그리고 잘 받아졌는지 확인하기 위해 로그로 출력. 

    함수를 만들었으면 호출하는 것도 잊지 말자.

    디바이스의 위도/경도를 가져와서 getWeather 를 호출해야 하므로, 위도/경도를 가져오는 함수에서 호출하는 코드를 넣어준다. 

    getLocation = async () => {
        try {
          const response = await Location.requestPermissionsAsync();
          console.log(response);
          const { 
            coords: { latitude, longitude } 
          } = await Location.getCurrentPositionAsync();
          // Send Geolocation data to Method
          this.getWeather( latitude, longitude );
          console.log(coords.latitude, coords.longitude);
        } catch (error) {
          Alert.alert("Can't find you.", "Please Try Again!")
        }
      }

     

    이렇게 짜면 API 를 호출하는 것은 완성. 데이터가 잘 오는지 확인해보자. 아래 스크린샷처럼 Return 값이 찍히면 성공적인 것. 

    아직 화면에 데이터를 뿌려주진 않았기때문에 프론트에서는 변화가 없다. 

     

     

     

    App.js 전체 코드

    import React from 'react';
    import { StyleSheet, Text, View } from 'react-native';
    import { Alert } from "react-native";
    import * as Location from 'expo-location';
    import axios from "axios";
    
    // 보안을 위해 Masking
    const API_KEY = "3cdc3160-93e9-****-****-************";
    
    export default class extends React.Component {
      
      // API 로 Axios Fetch
      getWeather = async(latitude, longitude) => {
        const { data } = await axios.get(
        `http://api.airvisual.com/v2/nearest_city?lat=${latitude}&lon=${longitude}&key=${API_KEY}`
        );
        console.log(data);
      }
      
      getLocation = async () => {
        try {
          const response = await Location.requestPermissionsAsync();
          console.log(response);
          const { 
            coords: { latitude, longitude } 
          } = await Location.getCurrentPositionAsync();
          // Send Geolocation data to Method
          this.getWeather( latitude, longitude );
          console.log(coords.latitude, coords.longitude);
        } catch (error) {
          Alert.alert("Can't find you.", "Please Try Again!")
        }
      }
      
      componentDidMount() {
        this.getLocation();
      }
      render() {
        return (
          <View style={styles.container}>
            <Text style={styles.title}>Hello World!</Text>
          </View>
        );
      }
    }
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        backgroundColor: 'blue',
        alignItems: 'center',
        justifyContent: 'center',
      },
      title: {
        fontSize: 30,
        color: 'white'
      }
    });
    

     

     

     

    댓글

Designed by Tistory.