2022/09/09
[NextJs]Google Mapでマーカーをセンターに表示するコンポーネントの作成
概要
会社概要やイベント詳細ページなど、地図を表示する必要がある際に使えるコンポーネントを作成しました。
NextJs(React 18)用です。
実装内容
必要なもの
事前に@react-google-maps/apiをインストールします。
% yarn add @react-google-maps/api
作ったコンポーネント
import { Libraries } from '@googlemaps/js-api-loader'
import { GoogleMap, MarkerF, useJsApiLoader } from '@react-google-maps/api'
import { CSSProperties, useState } from 'react'
interface Props {
lat: number
lng: number
mapContainerStyle?: CSSProperties
}
const LocationMap = ({ lat, lng, mapContainerStyle }: Props) => {
const [libraries] = useState<Libraries>(['geometry', 'drawing']) // 必要なライブラリーを指定します。
const { isLoaded } = useJsApiLoader({
id: 'google-map-script',
googleMapsApiKey: /* ここにGCPで発行したAPIキーを指定します。 */,
libraries,
})
if (isLoaded) {
return (
<GoogleMap
mapContainerStyle={
mapContainerStyle || { height: '450px', width: '100%' }
}
center={{ lat, lng }}
zoom={16}
>
<MarkerF position={{ lat, lng }} />
</GoogleMap>
)
} else {
return <></>
}
}
export default LocationMap
注意点
- React 18では、
MarkerF
を使わないとマーカーが表示されませんでした。 useJsApiLoader
を使って、すでに外部scriptをロードしたかどうか判定しないと、エラーになるケースがあります。
以上です。
関連する記事

【1行】JavascriptでCookieの全削除
たまにやるCookie全削除のJavascriptです

Nuxt2からNuxt3への移行とNextJSとNuxt3の比較について
弊社ホームページとブログサイトをNuxt2からNuxt3ベースに移行しました。

[NextJs]Google Mapでマーカーをセンターに表示するコンポーネントの作成
NextJsアプリ内で、Google Mapを表示して、中心にマーカーを配置するコンポーネントを作成しました。

Next.js + TailwindCSS + Reduxのプロジェクト立ち上げ時のメモ
Next.js + Tailwind CSS + Reduxのプロジェクト作成時の操作ログです。