LoginSignup
7
2

More than 3 years have passed since last update.

React GoogleMapAPIで地名や住所から緯度経度を取得する方法

Last updated at Posted at 2021-01-15

はじめに

今回は、地名や住所を入力して緯度と経度の情報を取得する方法をまとめました。
これができると、入力した地名にピンを立てたり、地図が移動したりできるのではないかと思います。
Reactのライブラリreact-geocodeを使用します。
単にマップを表示させたいという方はこちらをご参考ください。
事前にGoogleMapのAPIキーの取得と有効化、GeocodingAPIの有効化をお願い致します。

参考サイト

地名から緯度経度を取得するパターンと緯度経度から地名を取得するパターン両方載っています。
今回はHow to get lat and lng from addressで調べました。
https://www.npmjs.com/package/react-geocode

導入方法

まずはライブラリを利用する準備をします。
react-geocodeの最新バージョンを調べます。

$ npm info react-geocode

結果の一部がこちら

react-geocode@0.2.2 | MIT | deps: 1 | versions: 15
A module to transform a description of a location (i.e. street address, town name, etc.) into geographic coordinates (i.e. latitude and longitude) and vice versa.
https://github.com/shukerullah/react-geocode#readme

今の最新バージョンはreact-geocode@0.2.2でしたので、これをyarn addします。

$ yarn add react-geocode@0.2.2

これでこのプロジェクトでreact-geocodeが使えるようになりました。

地名から緯度経度を取得(コードの中)

まずはライブラリをimport

Geo.js
import Geocode from "react-geocode";

アロー関数の中はこんな感じで書きます。

Geo.js
const Geo = () => {

    Geocode.setApiKey("YOUR_APIKEY");
    Geocode.fromAddress("Eiffel Tower").then(
        response => {
            const { lat, lng } = response.results[0].geometry.location;
            console.log(lat, lng);
        },
        error => {
            console.error(error);
        }
    );
    return (
        <div>
            <h1>map</h1>
        </div>
    )
}

検証モードでconsoleを見ると、エッフェル塔の緯度と経度が確認できるかと思います。
下のdiv要素が無いとreturnするものが無いですというエラーが発生するので、とりあえず適当に入れています。
YOUR_APIKEYのところにご自身の取得したGoogleMapのAPIキーを入力してください。

地名から緯度経度を取得(画面で入力した地名)

先ほどの"Eiffel Tower"の部分を画面上で入力した地名に置き換えたいと思います。
まずはinputタグとbuttonタグで入力する部分を準備します。
先ほどのh1タグの下に

Geo.js
 <h1>map</h1>
 <input type='text'
        onChange={(e) => {
        setPlace(e.target.value)
 }}></input>
 <button onClick={() => {
         PushData();
 }}>search</button>

そして緯度経度を取得するコードの部分を関数に入れてあげます。
ボタンを押したらこの関数が走るように設定します。

Geo.js
const [place, setPlace] = useState('');
    const PushData=()=> {
        Geocode.setApiKey("YOUR_APIKEY");
        Geocode.fromAddress(place).then(
            response => {
                const { lat, lng } = response.results[0].geometry.location;
                console.log(lat, lng);
            },
            error => {
                console.error(error);
            }
        );
    }

入力欄が変更されるとsetPlace関数が動いて、placeに入力した値が入ります。
searchボタンが押されると入力した地名の緯度と経度が取得できます。

あっ、useStateのimportもお忘れなく!

Geo.js
import React, { useState } from 'react';

終わりに

今回は入力した地名から緯度と経度を取得するまでをご紹介しました。
次の投稿で取得した緯度経度を用いて、Googleマップにピンの立て方をまとめてみたいと思います。
firebaseも使います。
最後まで読んでいただきありがとうございます。

7
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
2