google maps apiで地図を作る

2024-09-21

react
Example Image

google maps apiを使って、マーカーを設置した地図を表示させるアプリを作ります。

react google mapsというライブラリを用いることで、google maps apiを簡単にreactアプリに組み込むことができます。

Google Cloud Platform アカウントをつくって、 Google Maps API キーとMAP IDを取得しておきます。

下記コマンドでプロジェクトにライブラリをインストールします。

npm install @vis.gl/react-google-maps

取得したGoogle Maps API キーとMAP IDを.env.localファイルに設定します。

地図とマーカーを表示させるためのコンポーネントを作成します。

import React from 'react';
import { APIProvider, Map, AdvancedMarker } from '@vis.gl/react-google-maps';

const GoogleMap = () => {
  const apiKey = process.env.NEXT_PUBLIC_GOOGLE_MAP_API_KEY;
  const mapId = process.env.NEXT_PUBLIC_GOOGLE_MAP_ID;

  if (!apiKey) {
    return <div>Google Maps API key is not set</div>;
  }

  const center = { lat: 35.658581, lng: 139.745433 };
  const marker = { position: { lat: 35.658581, lng: 139.745433 }, title: '東京タワー' };

  return (
    <APIProvider apiKey={apiKey}>
      <Map
        style={{ width: '800px', height: '700px' }}
        defaultCenter={center}
        defaultZoom={13}
        gestureHandling={'greedy'}
        disableDefaultUI={true}
        mapId={mapId}
      >
        <AdvancedMarker
          position={marker.position}
          title={marker.title}
        />
      </Map>
    </APIProvider>
  );
};

export default GoogleMap;

作成したコンポーネントを任意のページにインポートして使用するとで、地図を表示できるようになります。

share