GoogleMap の infowindow 内でクリックイベントを発火させる

2021年12月20日

GoogleMap で地図上にマーカーを設置し、それをクリックすると吹き出しが表示されます。

そこにボタンを配置してクリックイベントを発火させようとしましたが、動きませんでした。

理由が下記の為との事。

GoogleMapのマーカーをクリックしたときのウィンドウ(InfoWindow)内にボタンを配置した場合、 普通のボタンのように(click)=onClick()みたいにしてもコンポーネント内の要素ではなくなるためonClick()関数が呼ばれません。

上の記事では domready を使用して、DOM が構築されたタイミングでイベントを紐づけているようです。

今回は上記と別の方法をメモしておきたいと思います。

インポート

import Vue from 'vue/dist/vue.esm.js';

Vue.extend を使用するために Vue をインポートします。
ちなみにimport Vue from 'vue';だと下記のエラーが発生します。

You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.

これは「完全ビルド」ではなく「ランタイム限定ビルド」が実行されるのが原因のようです。

プロパティ作成

infowindow の content に割り当てるインスタンスのプロパティを宣言します。

export default {
    data() {
        return {
            ...
            infowindowVue: null,
            ...
        }
    },
    ...

インスタンス定義

インスタンスを定義します。
単純にボタンがあり、クリックすると hello world とアラートが出るものです。

    ...
    mounted (){
        this.infowindowVue = Vue.extend({
            data() {
                return {}
            },
            methods: {
                activateAlert: function() {
                    alert("hello world")
                }
            },
            template: '<button v-on:click="activateAlert()">button</button>'
        })
    },
    ...

インスタンス化

定義したインスタンスを new してインスタンス化します。
インスタンスの element を吹き出しの content 割り当てます。

this.infoWindows[i] = new window.google.maps.InfoWindow({
    content:  new this.infowindowVue().$mount().$el
});
YouTube

2021年12月20日