7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

vue2-google-mapsで右クリックした場所の座標を取得する

Last updated at Posted at 2019-10-23

はじめに

最近 Vue.js と Firebase を使ってウェブアプリケーションを作っています。
GoogleMap を Vue.js で利用するためのメジャーなライブラリは vue2-google-maps があります。

メジャーと言ってもサンプルが少なく、Map を右クリックしたときの座標取得の方法がわからず困っていたのですが、
色々と調べてその方法が分かったので紹介します。

手順概要

  • GoogleMap API のカスタムイベントを VueGoogleMaps で受け取れるようにする
  • 右クリックのイベントハンドラを登録する
  • $eventでオリジナルのDOMイベントを取得する

GoogleMap API のカスタムイベントを VueGoogleMaps で受け取れるようにする

デフォルトでは vue2-google-maps で取得できるイベントは click のみになります。
right click イベントを取得するためには use 時に autobindAllEvents: false を追加してやる必要があります。

import * as VueGoogleMaps from 'vue2-google-maps';
Vue.use(VueGoogleMaps, {
  installComponents: true,
  load: {
    key: 'APIキー',
    libraries: 'places'
  },
+  autobindAllEvents: false,
});

右クリックのイベントハンドラを登録する

これは単純に GmapMap のエレメントに @rightclick="ハンドラ()" を追加するだけです。

$eventでオリジナルのDOMイベントを取得する

Vue.js で GoogleMap API のオリジナル DOM イベントを取得するためには $event を使います。
place というハンドラを作り、先ほどのハンドラを @rightclick="place($event)" のように書きます。

ソース

<template>
  <card class="card-map">
    <div class="map">
      <div id="map">
          <GmapMap @rightclick="place($event)" :center="center" :zoom="zoom" :options="options" style="width: 100%; height: 100%;">
          </GmapMap>
      </div>
    </div>
  </card>
</template>
<script>

export default {
    data () {
        return {
            center: {lat: 35.71, lng: 139.72},
            zoom: 14,
        }
    },
    methods:{
        place(event){
            if (event) {
                var lat = event.latLng.lat()
                var lng = event.latLng.lng()
                console.log(lat + ", " + lng)
            }
        },
    }
};
</script>
<style></style>

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?