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

Angular7使用AGM npm包添加多条折线 如何中断首条后新增独立折线

问题根因

你当前只在模板中声明了单个<agm-polyline>实例,所有点位都绑定到同一条折线实例上;同时你没有渲染masterPolyLines中存储的已完成折线,且存储时直接传递了数组引用,清空当前绘制数组时也会影响已存储的数据,因此新绘制的点位会和旧折线连通。

调整方案

第一步:修改TS逻辑

  • 拆分变量:区分正在绘制的折线点位和已完成的折线列表
  • 存储已完成折线时做深拷贝,避免引用关联
// 定义变量
masterPolyLines: {id: number, routes: {lat: number, lng: number}[]}[] = []; // 所有已完成的折线
currentPolylinePoints: {lat: number, lng: number}[] = []; // 正在绘制的折线点位
showLine = false;

onLineRightClick(ev){
  console.log('event on right click',ev);
  // 仅当正在绘制的点位≥2个(形成有效折线)时才存入已完成列表
  if(this.currentPolylinePoints.length >= 2) {
    this.masterPolyLines.push({
      id: this.masterPolyLines.length + 1, // 动态生成唯一id
      routes: JSON.parse(JSON.stringify(this.currentPolylinePoints)) // 深拷贝切断引用关联
    });
  }
  // 清空当前绘制的点位,准备下一条折线
  this.currentPolylinePoints = [];
  console.log('masterPolyLines',this.masterPolyLines);
}

polyineMapClicked($event){
  console.log('event',$event);
  this.currentPolylinePoints.push({
    lat: $event.coords.lat,
    lng: $event.coords.lng
  });
  this.showLine = true;
  setTimeout(() => {
    this.divClick.nativeElement.click();
  }, 200);
  console.log('currentPolylinePoints',this.currentPolylinePoints);
}

第二步:修改HTML模板

遍历渲染所有已完成的折线,再单独渲染正在绘制的折线,两者互相独立:

<agm-map
  (mapClick)="polyineMapClicked($event)"
  [ngStyle]="{ height: '400px' }"
  [zoom]="zoom"
  [latitude]="lat"
  [longitude]="lng"
>
  <!-- 渲染所有已完成的折线 -->
  <agm-polyline 
    *ngFor="let line of masterPolyLines"
    strokeColor="#247ba0" 
    [editable]="true"
  >
    <agm-polyline-point
      *ngFor="let point of line.routes"
      [latitude]="point.lat"
      [longitude]="point.lng"
    ></agm-polyline-point>
  </agm-polyline>

  <!-- 渲染正在绘制的折线 -->
  <agm-polyline 
    strokeColor="#247ba0" 
    *ngIf="currentPolylinePoints.length > 0" 
    (polyPathChange)="updatePath($event)" 
    (lineRightClick)="onLineRightClick($event)" 
    [editable]="true"
  >
    <agm-polyline-point
      *ngFor="let point of currentPolylinePoints"
      [latitude]="point.lat"
      [longitude]="point.lng"
    ></agm-polyline-point>
  </agm-polyline>
</agm-map>

补充说明

如果不需要修改已完成的折线,可将已渲染折线的editable属性设为false,避免误操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 07:39:02