前回のTwitter埋め込みのようにGoogle MapをReactで埋め込む方法を考えます。
同じようにhttps://maps.googleapis.com/maps/api/js?key=XXXXXを読み込むことでAPI(google.maps.XXXなど)が使えるようになります。
ただし今回はかなりDOMをいじる必要があるので1から作るのはかなり面倒です。
React用Google Mapライブラリ
GitHubを見たところスター数4.3kのライブラリが2つありました。
使用数ではreact-google-mapsが圧倒的に多いですが2年ほどノーメンテなので、google-map-reactの方を使うことにします。
|
1 |
> yarn add google-maps-react @types/google-map-react |
マーカなど自分で作る必要はありますが、サンプルも多いので凝ったものを作りたければ適当にとってきて使えば良さそうです。
とりあえずサンプル通りに使ってみます。
明石海峡大橋の端らへんをGoogle Mapで適当に指して座標を得ます。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
const ako = { lat: 34.630575, lng: 135.032846 }; const AnyReactComponent = ({ text }: any) => { return ( <p style={{ backgroundColor: "red", width: 100, height: 100 }}>{text}</p> ); }; export const Map = () => { return ( <GoogleMapReact //bootstrapURLKeys={{ key: "" }} defaultCenter={ako} defaultZoom={11} > <AnyReactComponent {...ako} text="My Marker" /> </GoogleMapReact> ); }; |
key未指定なので開発モードで表示されます。
実際のGoogleMapと比べるとこんな感じ。

左上が座標になっている感じですね。
Tipsの要領でマーカーのCSSを書いてみます。
ついでに位置をわかりやすい場所に変更。
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
const ako = { lat: 34.630673, lng: 135.032917 }; const AnyReactComponent = ({ text }: any) => { return ( <div style={{ position: "absolute", transform: "translate(-50%, calc(-100% - 10px))", }} > <div style={{ padding: "5px", backgroundColor: "red", wordBreak: "keep-all", }} > {text} </div> <div style={{ position: "absolute", top: "100%", left: "50%", transform: "translate(-50%, 0)", width: 0, height: 0, borderStyle: "solid", borderWidth: "10px 10px 0px 10px", borderColor: "red transparent transparent transparent", }} /> </div> ); }; |
ごちゃごちゃしていますが下に三角形を付けて座標を調整しているだけです。

ここから機能を付け足していけばとりあえず色々できそうです。