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

Vue2中Google Maps折线首尾默认标记覆盖自定义标记的解决方法

解决Vue2-google-maps中DirectionsRenderer默认首尾标记覆盖自定义标记的问题

核心思路

通过给DirectionsRenderer设置suppressMarkers: true,关闭其自带的起点/终点默认标记,让你自定义的<GmapMarker>能够正常显示,不会被覆盖。

具体实现步骤

1. 更新DirectionsRenderer组件

修改你的DirectionsRenderer.js,添加suppressMarkers相关配置:

import { MapElementFactory } from "vue2-google-maps";

export default MapElementFactory({
    name: "directionsRenderer",

    ctr() {
        return google.maps.DirectionsRenderer;
    },

    events: [],

    mappedProps: {
        suppressMarkers: { type: Boolean }
    },

    props: {
        origin: { type: Object },
        destination: { type: Object },
        travelMode: { type: String },
        suppressMarkers: { type: Boolean, default: false }
    },

    afterCreate(directionsRenderer) {
        let directionsService = new google.maps.DirectionsService();

        this.$watch(
            () => [this.origin, this.destination, this.travelMode, this.suppressMarkers],
            () => {
                let { origin, destination, travelMode, suppressMarkers } = this;
                if (!origin || !destination || !travelMode) return;

                directionsService.route(
                    {
                        origin,
                        destination,
                        travelMode
                    },
                    (response, status) => {
                        if (status !== "OK") return;
                        directionsRenderer.setDirections(response);
                        directionsRenderer.setOptions({ suppressMarkers });
                    }
                );
            }
        );
    }
});

2. 在模板中启用标记隐藏

在Vue组件的模板里,给<DirectionsRenderer>添加:suppressMarkers="true"属性:

<template>
  <div>
    <GmapMap
      :center="center"
      :zoom="zoom"
      map-type-id="roadmap"
      style="width: 100%; height: 300px"
      ref="map"
    >
      <GmapMarker
        v-for="(m, index) in markers"
        :key="index"
        :ref="`marker${index}`"
        :position="m.position"
        :clickable="true"
        :icon="m.icon"
      />
      <DirectionsRenderer
        v-if='start!=null'
        travelMode="DRIVING"
        :origin="origin"
        :destination="destionation"
        :suppressMarkers="true"
      />
    </GmapMap>
  </div>
</template>

效果说明

设置完成后,DirectionsRenderer只会绘制两点间的折线路线,不再生成默认的红色首尾标记,你自定义的标记会正常显示在地图上且不会被覆盖。

内容的提问来源于stack exchange,提问作者Zia

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 00:01:15