0
3

More than 1 year has passed since last update.

ReactでGoogleMapsAPIを使う(#2地図に複数マーカーを表示)

Last updated at Posted at 2021-11-10

前回記事でReactでGoogleMapsAPIを用いて地図の単純表示を行いました。
今回も同様にGoogleMapsAPIの公式ドキュメントに準拠しつつ、地図上にマーカーを表示していきます。
尚、マーカーは複数でも対応できるようにしていきます。

前回記事で作ったコンポーネントの確認

地図表示だけのために作ったコンポーネントはこんな感じでした。

Test.js
import { Wrapper} from "@googlemaps/react-wrapper";
import Map from "./Map";

export default function Test(){

return (

<Wrapper apiKey={ここにAPIkey} >
  <Map/>
</Wrapper>
)
}
Map.js
import {useRef,useEffect,useState} from 'react';

export default function Map(){
  const ref = useRef(null);
  const [map, setMap] = useState();

 useEffect(() => {
  if (ref.current && !map) {
    setMap(new window.google.maps.Map(ref.current, {
       center:{
          lat: 35.6809591,
          lng: 139.7673068,
      },
      zoom:8,
      mapTypeControl: false,
      streetViewControl: false,
      fullscreenControl: false,
    }));

  }
}, [ref, map]);

return(
    <div ref={ref} style={{height:500, width:500}} />
  )
}

まずはMarkerコンポーネントを作る

こんな感じでMarkerのコンポーネントを作っていきます。

Marker.js
import {useState,useEffect} from 'react'

export default function Marker(options){
  const [marker, setMarker] = useState();

  useEffect(() => {
    if (!marker) {
      setMarker(new google.maps.Marker());
    }

    return () => {
      if (marker) {
        marker.setMap(null);
      }
    };
  }, [marker]);

  useEffect(() => {
    if (marker) {
      marker.setOptions(options);
    }
  }, [marker, options]);

  return null;
};

Mapコンポーネントを修正する

Mapコンポーネントを↓のように修正(returnの後を少し書き足し、それに合わせて上部も少し修正)し、google.maps.Mapオブジェクトを、Mapコンポーネントの子要素に渡せるようにします。こうすることで、Mapコンポーネントの子要素にMarkerコンポーネントを配置した際に、google.maps.Mapオブジェクトを渡せます。

Map.js
import React,{useRef,useEffect,useState} from 'react';

export default function Map({children}){
  const ref = useRef(null);
  const [map, setMap] = useState();

 useEffect(() => {
  if (ref.current && !map) {
    setMap(new window.google.maps.Map(ref.current, {
       center:{
          lat: 35.6809591,
          lng: 139.7673068,
      },
      zoom:14,
      mapTypeControl: false,
      streetViewControl: false,
      fullscreenControl: false,
    }));

  }
}, [ref, map]);

return(  <>
    <div ref={ref} style={{height:500, width:500}} />
    {React.Children.map(children, (child) => {
      if (React.isValidElement(child)) {
        return React.cloneElement(child, { map });
      }
    })}
  </>
  )
}

Test.jsコンポーネントを修正する

マーカーを表示する座標をpositionsという名前で配列に格納しておきます。
また、MarkerコンポーネントをMapコンポーネントの子要素の位置に入れるとともに、
map関数を使うことでpositionsに格納した各座標をレンダリングしていきます。
※positionsに格納された座標が一つであれば、当然、単一Markerのレンダリングとなります。

Test.js
import { Wrapper} from "@googlemaps/react-wrapper";
import Map from "./Map";
import Marker from "./Marker";

export default function Test(){

const positions =[
  {
          lat: 35.6809591,
          lng: 139.7673068,
      },
      {
          lat: 35.675069,
          lng: 139.763328,
      }
  ]

return (

<Wrapper apiKey={"ここにAPIkey"} >
  <MyMap>
  {positions.map(p=><Marker position={p}/>)}
  </MyMap>
</Wrapper>
)
}

完成!!

2021-11-11 0.48.35.png

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