You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

vue-google-map中如何让InfoWindow显示在Marker上方

解决vue-google-map中InfoWindow附着Marker上方的问题

要让InfoWindow像官方示例那样绑定到Marker并显示在其上方,核心是获取Marker的原生Google Maps实例,然后将其关联到InfoWindow组件上。下面是具体实现步骤:

1. 给Marker组件添加ref获取实例

在你的<gmap-marker>标签上添加ref属性,这样Vue就能访问到该组件实例,进而拿到原生的Google Maps Marker对象:

<gmap-map :center="center" :zoom="7" style="width: 100%; height: 300px">
  <!-- 给Marker添加ref,用于获取实例 -->
  <gmap-marker 
    ref="targetMarker"
    :position="markerPosition"
    @click="toggleInfoWindow"
  ></gmap-marker>

  <!-- InfoWindow不再用position,而是绑定marker属性 -->
  <gmap-info-window 
    :marker="boundMarker"
    :visible="isInfoWindowOpen"
  >
    <div>你的InfoWindow内容</div>
  </gmap-info-window>
</gmap-map>

2. 在Vue组件中获取原生Marker对象并关联

vue-google-maps的Marker组件会把原生的Google Maps Marker实例暴露在$markerObject属性下。我们在点击事件中获取这个对象,然后绑定到InfoWindow的marker属性上:

export default {
  data() {
    return {
      center: { lat: 39.9042, lng: 116.4074 }, // 示例中心点
      markerPosition: { lat: 39.9042, lng: 116.4074 }, // Marker位置
      boundMarker: null, // 用于绑定的原生Marker对象
      isInfoWindowOpen: false // 控制InfoWindow显示隐藏
    };
  },
  methods: {
    toggleInfoWindow() {
      // 获取Marker的原生Google Maps实例
      this.boundMarker = this.$refs.targetMarker.$markerObject;
      // 切换InfoWindow显示状态
      this.isInfoWindowOpen = !this.isInfoWindowOpen;
    }
  }
};

3. 多Marker场景的处理(如果需要)

如果你是循环渲染多个Marker,可以用数组形式的ref,通过索引获取对应Marker的实例:

<gmap-map :center="center" :zoom="7" style="width: 100%; height: 300px">
  <gmap-marker 
    v-for="(item, index) in markerList"
    :key="index"
    ref="markers"
    :position="item.position"
    @click="openMarkerInfo(index)"
  ></gmap-marker>

  <gmap-info-window 
    :marker="boundMarker"
    :visible="isInfoWindowOpen"
  >
    <div>{{ currentMarkerContent }}</div>
  </gmap-info-window>
</gmap-map>

对应的script部分:

export default {
  data() {
    return {
      center: { lat: 39.9042, lng: 116.4074 },
      markerList: [
        { position: { lat: 39.9042, lng: 116.4074 }, content: "Marker 1" },
        { position: { lat: 31.2304, lng: 121.4737 }, content: "Marker 2" }
      ],
      boundMarker: null,
      isInfoWindowOpen: false,
      currentMarkerContent: ""
    };
  },
  methods: {
    openMarkerInfo(index) {
      const marker = this.$refs.markers[index];
      this.boundMarker = marker.$markerObject;
      this.currentMarkerContent = this.markerList[index].content;
      this.isInfoWindowOpen = true;
    }
  }
};

关键说明

  • $markerObject:这是vue-google-maps组件提供的核心属性,专门用于获取底层的Google Maps原生对象,是实现绑定的关键。
  • InfoWindow的marker属性:绑定原生Marker对象后,InfoWindow会自动附着在Marker的上方,无需手动设置position,位置会和官方示例完全一致,且Marker移动时InfoWindow会自动跟随。

内容的提问来源于stack exchange,提问作者A. L

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:27:13