如何获取Google Map JS编辑完成后的polyline(折线)坐标?
Google Maps Polyline 编辑后坐标不同步修复方案
问题根因
Google Maps DrawingManager 仅在折线首次绘制完成时触发
polylinecomplete事件返回初始坐标,折线进入编辑状态后的顶点修改、线段拖拽、顶点新增/删除操作,不会主动同步到你初始化时存储的坐标数组,需要额外监听对应事件实现数据同步。
修复步骤
- 第一步:在
polylinecomplete事件回调中,给生成的polyline实例绑定set_at(顶点坐标修改)、insert_at(新增顶点)、remove_at(删除顶点)三个事件,覆盖所有编辑场景 - 第二步:每次上述事件触发时,调用
getPath().getArray()主动拉取最新的坐标数组,更新本地存储的坐标变量 - 第三步:Angular项目中需要用
NgZone.run()包裹数据赋值逻辑,确保Google Maps异步上下文里的变量变更能被Angular变更检测捕获,触发视图更新
核心代码示例
import { NgZone } from '@angular/core'; export class AppComponent { polylinePoints = []; drawingManager: google.maps.drawing.DrawingManager; // 先在构造函数注入NgZone constructor(private ngZone: NgZone) {} initDrawingManager() { // 原有drawingManager初始化逻辑中,补充polylinecomplete的回调监听 this.drawingManager.addListener('polylinecomplete', (polyline: google.maps.Polyline) => { // 存储初始坐标 this.updatePolylinePoints(polyline.getPath()); const path = polyline.getPath(); // 监听顶点修改 path.addListener('set_at', () => this.updatePolylinePoints(path)); // 监听新增顶点 path.addListener('insert_at', () => this.updatePolylinePoints(path)); // 监听删除顶点 path.addListener('remove_at', () => this.updatePolylinePoints(path)); // 如果开启了折线整体拖拽,额外监听dragend事件 polyline.addListener('dragend', () => this.updatePolylinePoints(polyline.getPath())); }); } // 封装公共的坐标更新方法 private updatePolylinePoints(path: google.maps.MVCArray<google.maps.LatLng>) { this.ngZone.run(() => { this.polylinePoints = path.getArray().map(latLng => ({ lat: latLng.lat(), lng: latLng.lng() })); }); } }
优化建议
- 组件销毁时,手动移除所有绑定的事件监听器,避免内存泄漏
- 可根据业务需求过滤重复的坐标更新触发,减少不必要的变量赋值
内容的提问来源于stack exchange,提问作者Sai Charan
相关产品推荐
相关产品推荐

