Cute Dog Bopping Head
본문 바로가기
Study IT/Web-App

[React] 간단한 날씨 웹앱 만들어보기 - openweathermap 에서 날씨 API 가져오기, axios 사용

by 찾 2021. 4. 26.

 

https://openweathermap.org/

이전에 longitude, latitude를 가져오는 과정을 다뤘었는데,

이를 이용해서 해당 위치의 날씨 정보를 가져오는 API가 있다고 한다. Openweathermap이 그것!

 

위도와 경도를 저장해주는 코드로 조금 고쳐주고,

 

import React from "react";
import { Alert } from "react-native";
import Loading from "./Loading";
import * as Location from "expo-location";

const API_KEY = "나의 API 키!!!!!!!!"; 

export default class extends React.Component {
  state = { isLoading: true };
  getLocation = async () => {
    try {
      await Location.requestPermissionsAsync();
      const {
        coords: { latitude, longitude },
      } = await Location.getCurrentPositionAsync();
      this.setState({ isLoading: false });
      // Send to API and get Weather!
    } catch (error) {
      Alert.alert("Can't find you.", "So Sad");
    }
  };
  componentDidMount() {
    this.getLocation();
  }
  render() {
    const { isLoading } = this.state;
    return isLoading ? <Loading /> : null;
  }
}

저어어어 위에 있는 openweathermap 홈페이지를 들어가서, 로그인 회원가입을 해준다.

그 후 home의 api key로 들어가면, (home.openweathermap.org/api_keys)

 

key 밑에 내 키가 뜬다. 그것을 const API_KEY에 저장해주기!

 

이것이 우리가 사용할 API에 대한 문서.

 

인터넷에서 해당 정보를 불러오려면 axios가 필요하므로, 이를 add해주기.

그 후 해당 정보를 사용해서 이렇게 코드 변경.

 

import React from "react";
import { Alert } from "react-native";
import Loading from "./Loading";
import * as Location from "expo-location";
import axios from "axios";

const API_KEY = "나의 API 키~~~~~";

export default class extends React.Component {
  state = { isLoading: true };
  getWeather = async (latitude, longitude) => {
    const { data } = await axios.get(
      `http://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`
    ); // 쌍따옴표, 홑따옴표 아니고 1 옆에 있는 백틱 ` 을 사용. 그래야 안에 변수 넣어줄 수 있음
    console.log(data);
  };
  getLocation = async () => {
    try {
      await Location.requestPermissionsAsync();
      const {
        coords: { latitude, longitude },
      } = await Location.getCurrentPositionAsync();
      this.getWeather(latitude, longitude);
      this.setState({ isLoading: false });
      // Send to API and get Weather!
    } catch (error) {
      Alert.alert("Can't find you.", "So Sad");
    }
  };
  componentDidMount() {
    this.getLocation();
  }
  render() {
    const { isLoading } = this.state;
    return isLoading ? <Loading /> : null;
  }
}

신기한 부분은, 백틱을 사용해야 변수를 넣어줄 수 있다는 것이다.

따옴표를 사용하면 해당 부분이 적용되지 않고 그냥 하나의 url 주소처럼 보인다.

 

 

댓글