LoginSignup
5
2

More than 3 years have passed since last update.

VuejsでGoogleMapAPIを使用して現在地を中心にしたマップを表示する

Last updated at Posted at 2020-05-28

VuejsでGoogleMapAPIを使用して現在地を中心にしたマップを表示する

概要

  • VuejsのGoogleMapのプラグインを使わないで現在地を中心としたマップを表示する

環境

  • Mac Catalina(10.15.2)
  • Node (v12.7.0)
  • VSCode

前提

  • VueCLIを使用する
  • GoogleMapAPIのKeyは取得済み

手順

プロジェクトを立ち上げる

  • 以下のコマンドでプロジェクトフォルダ新規作成する
vue create google-map-vue-practice
  • プロジェクトフォルダをVSCodeで開く

ファイルを変更する

  • public/index.htmlに以下のコードを追加する
    • API_KEYは自身のGoogleMapAPIKeyに置き換える
index.html
        <div id="app"></div>
    <!-- built files will be auto injected -->
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=initMap">
  </script>
  </body>
  • App.vueを以下のようにする
    • navigator.geolocation.getCurrentPosition
      • 現在地を取得する関数
    • window.google.maps.LatLng
      • 緯度経度のオブジェクトを作る関数
    • window.google.maps.Map
      • GoogleMapを作成する関数
    • window.google.maps.Marker
      • マーカーを作成する関数
App.vue
<template>
  <div id="app">
    <div id="map" ref="map" />
  </div>
</template>

<script>

export default {
  name: "App",
  data: () => ({
    map:null
  }),
  mounted() {
    if (navigator.geolocation) {
      // callback関数内でthis使えないため
      let vm = this
      navigator.geolocation.getCurrentPosition(
        function(position){
          let latlng = new window.google.maps.LatLng(
            position.coords.latitude,
            position.coords.longitude
          );
          vm.map = new window.google.maps.Map(vm.$refs["map"], {
            center: latlng,
            zoom: 4
          })
          new window.google.maps.Marker({
            position: latlng,
            map: vm.map
          })
        }
      )
    }
  }
};
</script>

<style>
#map {
  height: 600px;
  background: gray;
}
</style>

実行する

  • 以下のコマンドでローカル実行する
npm run serve
  • http://localhost:8080/でブラウザを開くと以下の画面が出る

スクリーンショット 2020-05-28 17.20.51.png

終わりに

  • 今回のプロジェクトを私のリポジトリで公開
    • 上記のコード以外も少し混ざってますのでご了承ください
5
2
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
5
2