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

如何在@angular/google-maps中拖拽路线后获取端点坐标

基于@angular/google-maps实现拖拽路线更新点位的实现方案

实现步骤

1. 配置路线可拖拽属性

首先确保你的routeOptions中开启了拖拽权限,否则无法拖动路线端点或路径调整路线:

// 组件类中定义路线渲染配置
routeOptions: google.maps.DirectionsRendererOptions = {
  draggable: true, // 核心配置,允许拖拽调整路线
  // 其他自定义配置,比如隐藏默认标记、修改路线颜色等
  // suppressMarkers: true,
  // polylineOptions: { strokeColor: '#1976d2' }
};

2. 获取MapDirectionsRenderer组件实例

通过@ViewChild装饰器获取模板中map-directions-renderer的组件实例,该实例暴露了原生Google Maps DirectionsRenderer对象:

// 首先导入依赖
import { ViewChild } from '@angular/core';
import { MapDirectionsRenderer } from '@angular/google-maps';

@Component({
  // 你的组件配置
})
export class YourMapComponent {
  // 获取模板中的map-directions-renderer实例
  @ViewChild(MapDirectionsRenderer) directionsRenderer: MapDirectionsRenderer;

  // 其他原有变量:loadedCenter、center、options、showDirectionsRoute、directionsRoute等
}

你现有模板无需修改,保留原来的(directionsChanged)事件绑定即可。

3. 在路线变更事件中获取最新路线数据

directionsChanged事件会在路线被拖拽调整后触发,虽然事件没有返回值,但可以通过刚才拿到的原生实例调用官方API获取最新的路线信息:

// 组件类中的事件处理方法
setDirectionsOnDrag() {
  // 先判断实例是否已初始化,避免报错
  if (!this.directionsRenderer?.directionsRenderer) return;

  // 调用原生API获取最新路线结果
  const latestDirections = this.directionsRenderer.directionsRenderer.getDirections();
  // 两点之间的路线取第一条路线的第一个路段即可
  const targetLeg = latestDirections.routes[0].legs[0];

  // 提取你需要的业务数据
  const newOrigin = targetLeg.start_location.toJSON(); // 新起点坐标 {lat, lng}
  const newDestination = targetLeg.end_location.toJSON(); // 新终点坐标 {lat, lng}
  const routeDistance = targetLeg.distance.value; // 路线总距离(单位:米)
  const routeDuration = targetLeg.duration.value; // 路线预计耗时(单位:秒)

  // 此处可更新你的业务逻辑,比如同步更新地址输入框的坐标、重新计算配送费用等
  console.log('新目的地坐标:', newDestination);
}

注意事项

  • 如果你的map-directions-renderer上绑定了*ngIf指令,只有当条件为真时@ViewChild才能拿到实例,调用前做好非空判断即可。
  • 如果你自定义了路线标记,可在routeOptions中设置suppressMarkers: true隐藏默认标记,自己额外添加map-marker组件绑定坐标即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 15:57:02