ReactでAxiosを使ってGoogleAPIを叩いてみた


概要

今回はReactでaxiosライブラリを使ってGoogleAPIを叩いてみたので、その時のメモです。
axioは超使いやすいので、ReactでAPIを叩いてみようという人にはオススメです。

とりあえずターミナル上で

yarn add axios

でインストールしてください。

詳細
https://www.npmjs.com/package/axios

使ったGoogleAPIについて

今回はGoogle Maps Geocoding APIを使いました。簡単にいうと、建物の名前(通天閣など)を渡すと
その経度と緯度を返してくれるようなAPIです。Googleさんすごいですね!!

詳細

axiosについて

axiosはGETやPOSTなど、様々なHTTPリクエストを投げることができるメソッドです。
今回はGETリクエストを送って、APIのデータを受け取る方法について紹介します。

axios
    .get(エンドポイント, { params: {送りたいパラメーターの指定} })
    .then((results) => {
        // 通信に成功してレスポンスが返ってきた時に実行したい処理
    }
    .catch((error) => {
        // 通信に失敗してレスポンスが返ってこなかった時に実行したい処理
    }

簡単なaxiosの使い方を説明します。axios.getは引数を二つとり、
第一引数にはエンドポイント、第二引数に渡したいパラメータをparamsで指定します。
そして、レスポンスが返ってきたかどうかで挙動が変わります。

レスポンスが返ってきた時
- 返ってきたデータがresultsの中に入り、thenが走る。

レスポンスが返ってこなかった時
- errorメッセージがerrorに入り、catchが走る。

このような流れでaxios.get()は動きます。

実際のコード例

以下に、axiosを使ったコードを載せます。

src/index.jsx

import React from 'react';
import ReactDOM from 'react-dom';

import App from './components/App';

ReactDOM.render(<App />, document.querySelector('.container'));

src/components/App.jsx

import React, { Component } from 'react';
import axios from 'axios';

const GEOCODE_ENDPOINT = 'https://maps.googleapis.com/maps/api/geocode/json';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      place: '通天閣', //ここに好きな場所を指定。
    };
  }
  handleGetLatAndLng() {
    // Google Maps APIが指定した必須パラメータ(この場合はaddress)をparamsに渡す。
    axios
      .get(GEOCODE_ENDPOINT, { params: { address: this.state.place } })
      .then((results) => {
      // 以下のGoogle API のレスポンスの例を元に欲しいデータを取得
        const data = results.data;
        const result = data.results[0];
        const location = result.geometry.location;
        this.setState({
          address: result.formatted_address,
          lat: location.lat,
          lng: location.lng,
        });
      },
      )
      .catch(() => {
        console.log('通信に失敗しました。');
      });
  }

  render() {
    return (
      <div className="app">
        <h1 className="app-title">緯度軽度検索</h1>
        <p> 土地名: {this.state.place} </p>
        <p> 経度: {this.state.lat}</p>
        <p> 経度: {this.state.lng}</p>
        <input
          type="button"
          value="経度・緯度を検索"
          onClick={() => this.handleGetLatAndLng()}
        />
      </div>
    );
  }
}

export default App;

Google API のレスポンスの例(JSON)

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "1600",
               "short_name" : "1600",
               "types" : [ "street_number" ]
            },
            {
               "long_name" : "Amphitheatre Pkwy",
               "short_name" : "Amphitheatre Pkwy",
               "types" : [ "route" ]
            },
            {
               "long_name" : "Mountain View",
               "short_name" : "Mountain View",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Santa Clara County",
               "short_name" : "Santa Clara County",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "California",
               "short_name" : "CA",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "United States",
               "short_name" : "US",
               "types" : [ "country", "political" ]
            },
            {
               "long_name" : "94043",
               "short_name" : "94043",
               "types" : [ "postal_code" ]
            }
         ],
         // 今回はこの部分のformatted_address, geometryのlat, lngを取得
         "formatted_address" : "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA",
         "geometry" : {
            "location" : {
               "lat" : 37.4224764,
               "lng" : -122.0842499
            },
            "location_type" : "ROOFTOP",
            "viewport" : {
               "northeast" : {
                  "lat" : 37.4238253802915,
                  "lng" : -122.0829009197085
               },
               "southwest" : {
                  "lat" : 37.4211274197085,
                  "lng" : -122.0855988802915
               }
           }
        },
        "place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
        "types" : [ "street_address" ]
     }
      ],
      "status" : "OK"
}

このようにコードを書き、【経度・緯度を検索】ボタンを押すと
通天閣の軽度、緯度を取得できるようになります。

ボタンを押す

通天閣の経度と緯度を取得できましたね!!

this.state = {
      place: '通天閣', //ここに好きな場所を指定。
    };

ここを変えて色々と試してみてください。

まとめ

axiosを使うと簡単にGoogle APIやTwitter APIを使うことができます。
他にもPOSTリクエストを送ったりdeleteリクエストを送ったり、様々な使い方があるみたいなので、
色々とこれから試していこうと思います。