@click在Google Maps Infowindow按钮中不起作用

时间:2018-06-23 06:26:05

标签: google-maps vue.js

在我的Vue应用程序中,我显示了带有标记的Google Map,这些标记是使用Axios从API中检索到的。当我单击一个标记时,它会显示一个带有按钮的信息窗口,其中有一个@click='show_details = !show_details'来切换带有详细信息的其他div。但是,这不起作用,我也不知道为什么。这是代码:

<template>
  <div class="map">
    <div class="google-map" id="map"></div>
    <div class="row justify-content-end">
      <div class="col-2">
        <div class="visit-details" v-show="show_details">details</div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'Map',
  data(){
    return {
      lat: 54.6,
      lng: -2,
      show_details: false
    }
  },
  methods: {
    renderMap(){
      const map = new google.maps.Map(document.getElementById('map'), {
        center: { lat: this.lat, lng: this.lng },
        zoom: 6,
        maxZoom: 20,
        minZoom: 3
      })

      axios.get('https://bla.json')
        .then(res => {
          res.data.forEach(doc => {
            let contentString = "<div @click='show_details = !show_details'>details</div>";
            let visitLatLng = {lat: doc.latitude, lng: doc.longitude};
            let marker = new google.maps.Marker({
              position: visitLatLng,
              title: doc.ground,
              map: map
            })
            let infowindow = new google.maps.InfoWindow({
              content: contentString
            });
            marker.addListener('click', function() {
              infowindow.open(map, marker);
            });
          })
        })
        .catch(error => console.log(error))
    }
  },
  mounted(){
    this.renderMap()
  }
}
</script>

<style>
</style>

2 个答案:

答案 0 :(得分:0)

Google 地图信息窗口不在 Vue.js 范围内!也许不是最干净的解决方案,但您可以使用全局函数来引用您的 Vue 函数,如下所示:

window.myGlobalFunction = this.myVueFunction;

在您的 InfoWindow 内容中

"<div><a onclick='myGlobalFunction(" + someParam + ")'>Hello</a></div>";

答案 1 :(得分:0)

创建 vue Infowindow 内容组件,传递数据,使用 $on 订阅事件,$mount vue 组件并将元素注入 infowindow。使用 $emit 触发 vue infowindow 组件事件。

InfoWindow.vue

<template>
    <div>
        ...
        <v-btn @click="selectLocation(item)">Select Location {{item.Name}}</v-btn>
        ...
    </div>
</template>

<script>
module.exports = {
    name: 'infowindow',
    props: [ 
        'item',
    ],
    methods: {
        selectLocation(item) {
          // emit click action in infowindow
          this.$emit('action:selectedLocation', item);
        },
    },
}
</script>

在打开信息窗口之前需要创建的代码部分:

...
import InfoWindowComponent from './InfoWindow.vue';
...

var InfoWindow = Vue.extend(InfoWindowComponent);
var instance = new InfoWindow({
    propsData: {
        item: item
    }
});

instance.$mount();

// parent subscribes to event from infowindow
instance.$on('action:selectedLocation', (item) => {
    // handle click action
});

var new_infowindow = new google.maps.InfoWindow({
    content: instance.$el,
});

new_infowindow.open(<map object>, <marker>);

来源: