1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

GoogleMapGeocodingAPIをReactで使用する

Posted at

やりたいこと

GoogleMapをアプリで使用する際に、場所の検索ができると思いますが、その機能をAPIでも実現したいです。
GoogleMapにはGeocodingAPIが用意されていて、場所の名前から緯度・経度を返してくれます。これをReactで使用するときのサンプルを紹介します。

前提等

サンプル

GoogleMapComponent.js
import React, { useContext } from "react";
import { GoogleApiWrapper, Map } from "google-maps-react";
import { MapStore } from "../../store/MapStore";

export const GoogleMapComponent = ({ google }) => {
  const { state, dispatch } = useContext(MapStore);
  const location = state.currentLocation;
  const [place, setPlace] = useState("");
  function handleChangePlace(e) {
    setPlace(e.target.value);
  }
  // 地名での検索
  function handleSearch() {
    if (place !== "") {
      const geocoder = new google.maps.Geocoder();
      // Geocodingの呼び出し
      geocoder.geocode(
        {
          address: place,
          region: "jp",
        },
        function (results, status) {
          if (status === "OK") {
            const geometryLoc = results[0].geometry.location;
            dispatch({
              type: "CHANGE_LOCATION",
              currentLocation: {
                latitude: geometryLoc.lat(),
                longitude: geometryLoc.lng(),
              },
            });
          }
        }
      );
    }
  }
  return (
    <input
      type="text"
      name="place"
      value={place}
      onChange={handleChangePlace}
    />
    <input type="button" value="検索する" onClick={handleSearch} />
    <Map
      google={google}
      zoom={15}
      center={{ lat: location.latitude, lng: location.longitude }}
      initialCenter={{ lat: location.latitude, lng: location.longitude }}
    />
  );
};

export default GoogleApiWrapper({
  apiKey: process.env.REACT_APP_GOOGLE_MAP_API_KEY,
})(GoogleMapComponent);

1
3
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
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?