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

如何让折线随可拖动路线更新且移除旧折线

解决拖动路线时旧折线残留的问题

问题出在每次directions_changed触发时,你都新建了一个Polyline实例但未移除旧的,导致地图上堆积多条折线。核心解决思路是维护折线实例的引用,确保每次更新前处理掉旧折线,下面是两种可行实现:

方案1:复用Polyline实例(推荐)

将Polyline变量提升到initMap函数作用域内,每次路线变化时直接更新它的路径,无需反复创建新实例,性能更优:

function initMap() {
    const map = new google.maps.Map(document.getElementById("map"), {
      zoom: 4,
      center: { lat: -24.345, lng: 134.46 }, // Australia.
    });
    const directionsService = new google.maps.DirectionsService();
    const directionsRenderer = new google.maps.DirectionsRenderer({
      draggable: true,
      map,
      panel: document.getElementById("panel"),
    });
    // 声明作用域内的polyline变量,初始为null
    let polyline = null;

    directionsRenderer.addListener("directions_changed", () => {
      const directions = directionsRenderer.getDirections();

      if (directions) {
        computeTotalDistance(directions);
        const path = google.maps.geometry.encoding.decodePath(directions.routes[0].overview_polyline);
        
        if (polyline) {
          // 已有折线,直接更新路径
          polyline.setPath(path);
        } else {
          // 首次创建折线实例
          polyline = new google.maps.Polyline({
            path: path,
            map: map
          });
        }
      }
    });
    displayRoute(
      "Perth, WA",
      "Sydney, NSW",
      directionsService,
      directionsRenderer
    );
  }

  // 以下函数保持不变
  function displayRoute(origin, destination, service, display) {
    service
      .route({
        origin: origin,
        destination: destination,
        waypoints: [
          { location: "Adelaide, SA" },
          { location: "Broken Hill, NSW" },
        ],
        travelMode: google.maps.TravelMode.DRIVING,
        avoidTolls: true,
      })
      .then((result) => {
        display.setDirections(result);
      })
      .catch((e) => {
        alert("Could not display directions due to: " + e);
      });
  }

  function computeTotalDistance(result) {
    let total = 0;
    const myroute = result.routes[0];

    if (!myroute) {
      return;
    }

    for (let i = 0; i < myroute.legs.length; i++) {
      total += myroute.legs[i].distance.value;
    }

    total = total / 1000;
    document.getElementById("total").innerHTML = total + " km";
  }

  window.initMap = initMap;

方案2:每次更新前移除旧折线

如果需要每次创建新实例,需先将旧折线从地图上移除:

function initMap() {
    const map = new google.maps.Map(document.getElementById("map"), {
      zoom: 4,
      center: { lat: -24.345, lng: 134.46 }, // Australia.
    });
    const directionsService = new google.maps.DirectionsService();
    const directionsRenderer = new google.maps.DirectionsRenderer({
      draggable: true,
      map,
      panel: document.getElementById("panel"),
    });
    // 保存旧折线的引用
    let oldPolyline = null;

    directionsRenderer.addListener("directions_changed", () => {
      const directions = directionsRenderer.getDirections();

      if (directions) {
        computeTotalDistance(directions);
        // 先移除旧折线
        if (oldPolyline) {
          oldPolyline.setMap(null);
        }
        // 创建新折线
        const polyline = new google.maps.Polyline({
          path: google.maps.geometry.encoding.decodePath(directions.routes[0].overview_polyline),
          map : map
        });
        // 更新旧折线引用为当前新折线
        oldPolyline = polyline;
      }
    });
    displayRoute(
      "Perth, WA",
      "Sydney, NSW",
      directionsService,
      directionsRenderer
    );
  }

  // 其余函数保持不变...

关键说明

  • 方案1更高效,避免了反复创建和销毁DOM元素,仅更新路径数据。
  • 两种方案的核心都是通过变量保留折线实例的引用,确保每次更新前能定位并处理旧折线。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 08:05:37