今回は、React.jsのアプリにGoogleMapのGeocodingAPIを組み込む手順を紹介します。
前提
Reactアプリはnpx create-react-app
で作成したものとする。 URL(https://ja.reactjs.org/docs/create-a-new-react-app.html)
GCP(GoogleCloudPlatform)でAPIキーを発行する
Mapの描画やジオコーディングを利用できるようにGoogle Developers Consoleで
Maps JavaScript API
とGeocoding API
を有効化- 認証情報からAPIキーを発行
- APIキーに
Maps JavaScript API
とGeocoding API
を利用できるようにする
を行っていきます。
Maps JavaScript APIとGeocoding APIを有効化

認証情報からAPIキーを発行


APIキーにMaps JavaScript APIとGeocoding APIを利用できるようにする

Reactアプリを作成
1 |
$ npx create-react-app google-geocoding-app |
ディレクトリに入ってアプリを起動
1 2 |
$ cd google-geocoding-app $ npm start |

ReactからGoogleMapAPIを利用するモジュールを組み込む
こちらの記事で紹介されているモジュールをインストールする
1 |
$ npm install --save @react-google-maps/api |
モジュールドキュメント(https://react-google-maps-api-docs.netlify.app/#section-getting-started)
ソースコードをいじる
.env
ファイルをsrcディレクトリと同じ階層に作成して、以下のように発行したGCPのAPIキーを設定する
1 |
REACT_APP_GOOGLE_MAP_API_KEY="APIキー" |
App.js
を編集し、入力情報をジオコーディングする画面を構築する。
ジオコーディングの公式サンプルはこちらhttps://developers.google.com/maps/documentation/javascript/examples/geocoding-simple
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
import React, { Component } from 'react'; import { GoogleMap, LoadScript, Marker } from '@react-google-maps/api'; import './App.css'; class App extends Component { googleGeocoder = null; constructor(props) { super(props); this.state = { locationName: '', center: { lat: -3.745, lng: -38.523 }, isShowMarker: false } } changeLocationName(e) { if (e.key === 'Enter') { this.geocode(); return; } this.setState({ locationName: e.target.value }); } geocode() { const geocoder = new window.google.maps.Geocoder(); geocoder.geocode({ address: this.state.locationName }, ( results, status ) => { if (status === 'OK') { let center = Object.assign({}, this.state.center); center = { lat: results[0].geometry.location.lat(), lng: results[0].geometry.location.lng() }; this.setState({ center, isShowMarker: true }); } }); } render() { const labelStyle = { margin: '20px', display: 'block' } const containerStyle = { width: '100%', height: '60vh' }; return ( <div> <label style={labelStyle}>Input LocationName:<input type='text' onChange={(e) => this.changeLocationName(e)} value={this.state.locationName} onKeyPress={(e) => this.changeLocationName(e)}/></label> <LoadScript googleMapsApiKey={process.env.REACT_APP_GOOGLE_MAP_API_KEY}> <GoogleMap mapContainerStyle={containerStyle} center={this.state.center} zoom={18} > { this.state.isShowMarker && <Marker position={this.state.center} /> } </GoogleMap> </LoadScript> </div> ); } } export default App; |
画面はこのような感じになっていれば完成です。

動作例:
マップを描画する部分
LoadScript
コンポーネントでラップした内部でGoogleMap
コンポーネントを設置して
マップを描画しています。
1 2 3 4 5 6 7 8 9 |
<LoadScript googleMapsApiKey={process.env.REACT_APP_GOOGLE_MAP_API_KEY}> <GoogleMap mapContainerStyle={containerStyle} center={this.state.center} zoom={18} > { this.state.isShowMarker && <Marker position={this.state.center} /> } </GoogleMap> </LoadScript> |
マップの中心地はステートで更新されます。
検索した場合にはisShowMarker
がtrueになるためマーカーも描画されます。
ジオコーディングする部分
LoadScript
コンポーネントがDOMに組み込まれるとwindow.google
オブジェクトをグローバルから参照できるようになります。
ジオコードする関数geocode
ではwindow.google.maps.Geocoder()
から取得したオブジェクトから
ステートで管理している地名(locationName
)で検索しています。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
geocode() { const geocoder = new window.google.maps.Geocoder(); geocoder.geocode({ address: this.state.locationName }, ( results, status ) => { if (status === 'OK') { let center = Object.assign({}, this.state.center); center = { lat: results[0].geometry.location.lat(), lng: results[0].geometry.location.lng() }; this.setState({ center, isShowMarker: true }); } }); } |
まとめ
- GoogleMapのジオコーディングを試したい場合はデベロッパーコンソールからAPIキーを発行し、
Geocoding API
を有効にする - ReactからGoogleMapAPIを利用するには
react-google-maps
モジュールがおすすめ