LoginSignup
0
0

More than 1 year has passed since last update.

GoogleMapPlatformのハローワールド with React

Posted at

はじめに

GoogleMapを使った何らかのWebサービスできないかな。と考えたので、GoogleMapPlatformを触ってみたくなった。

Webサービス作る方法として、React以外よく知らないので、Reactで開発できればなぁと思っている。

本題

リポジトリ作成

いつも通り、GitLabでリポジトリ作成してから、
「Reactの雛形作成」というissueを立てて作業開始。

記録を残すためにmasterブランチに直接プッシュせずに、MRを使ってマージしていく開発を遵守している。

だいたい個人開発って長く細く続けるので、記録を残していかないと、あの時何したかとか、あの時何でそうしたのかとか辿れないので。

Reactの雛形作成

npx create-react-app wanderlust --template typescript

を叩いてtypescriptのReact雛形を作成する。

.gitignoreファイルがなかったので
どこからか拾ってきたもの+αをとりあえず当てておく

# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# production
/build

# misc
.idea
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
.firebase

npm-debug.log*
yarn-debug.log*
yarn-error.log*
firebase-debug.log*
firestore-debug.log*
pubsub-debug.log*
ui-debug.log*

自動作成されたREADME.mdを編集して、諸々メモ書きしておく。
これも、作業と同時に変更しないと、よくわかんなくなるので。

READMEのテンプレはググると色々出てくるので、そちらを参考に。

書いた方が良いと思うのは、入れたライブラリの情報とか
もし後悔する予定ならライセンスとかかな

Google Map Platform

公式を参考に実施する。
https://developers.google.com/maps/gmp-get-started?hl=ja

をみながら

  • 請求先アカウントを作成する
  • Google Cloud Platform(GCP)にプロジェクトを作成
  • 請求先アカウントを作成したGCPプロジェクトにリンクする
  • Maps JavaScriptAPIを有効にする
  • APIキーを取得する

を実施。

その後、コードは、
https://developers.google.com/maps/documentation/javascript/overview?hl=ja#all
を参考に書いていく。

一旦、動作確認したいので
public/index.htmlに直接書く。

  <head>
    ...
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
    <style type="text/css">
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }

      /* Optional: Makes the sample page fill the window. */
      html,
      body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
    <script>
      let map;

      function initMap() {
        map = new google.maps.Map(document.getElementById("map"), {
          center: { lat: -34.397, lng: 150.644 },
          zoom: 8,
        });
      }
    </script>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <div id="map"></div>

    <!-- Async script executes immediately and must be after any DOM elements used in callback. -->
    <script
      src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=&v=weekly"
      async
    ></script>
  </body>

そのままだとReactのアイコンがグルグル画面出てきてしまうので、
src/index.tsxのAppをコメントアウトする。

ReactDOM.render(
  <React.StrictMode>
    {/*<App />*/}
  </React.StrictMode>,
  document.getElementById('root')
);

これで表示されるはず。

スクリーンショット 2021-05-26 9.00.22.png

ちなみに、APIキーを忘れると表示されない。
スクリーンショット 2021-05-26 8.47.04.png

React用に書き換えていく

流石にこのままだとReactって何。となるので、書き換えていく。

公式より
https://developers.google.com/maps/documentation/javascript/using-typescript
yarn add -D @types/google.maps でライブラリをインストールする。

Google Map PlatformのAPI読み込みのために便利なライブラリを見つけたので利用する。
https://www.npmjs.com/package/@googlemaps/js-api-loader
yarn add @googlemaps/js-api-loader

このライブラリを使ってReactコンポーネントを作成する。

import React, { useEffect } from 'react'
import { Loader } from '@googlemaps/js-api-loader'

const HelloMap: React.FC = () => {
  useEffect(() => {
    const loader = new Loader({
      apiKey: 'apiKey',
      version: 'weekly',
      libraries: []
    })
    const mapOptions = {
      center: { lat: -34.397, lng: 150.644 },
      zoom: 8,
    }

    loader
      .load()
      .then(() => {
        const ele = document.getElementById("map")
        if (ele) {
          new google.maps.Map(ele, mapOptions)
        }
      })
      .catch(e => {
        console.error(e)
      })

  }, [])
  return (
    <div id="map" style={{ height: '100vh' }} />
  )
}

height: '100vh'にしているのは、ちょっとサボり。
もしheight: '100%'にしたいんだ!って人がいたら、
src/index.css

#root,
.App {
  height: 100%;
}

を書き込もう。
何でって人は、height100%の計算方法についてググって。

App.tsx側で先ほど作ったHelloMapコンポーネントを呼び出すように書き換える。

import React from 'react'
import './App.css'
import HelloMap from './components/HelloMap'

function App() {
  return (
    <div className="App">
      <HelloMap />
    </div>
  )
}

export default App

この後、とりあえず表示するために変更した
public/index.htmlsrc/index.tsxを元に戻して、動作確認。

変わらずGoogleMapが表示されることを確認する。

心残り

  • Redux導入して、API読み込んだかフラグを保持するようにする
  • eslint導入
  • JS in CSS導入
  • etc...

とか実施しておきたい。。

まとめ

一番面倒なのは、Googleのアカウントを作って、APIキーを取得するところだと思う。
そうは言っても、ドキュメント充実しているので、読みながら進めればなんとかなる。

実作業時間は2時間あればハローワールドできますよ。

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