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

Angular中为Leaflet Routing Machine添加自定义标记的问题

解决方案

方案1:扩展TypeScript类型定义,兼容createMarker

报错原因是@types/leaflet-routing-machine的类型声明里未包含createMarker属性,手动扩展接口即可让TypeScript识别该配置项:

在项目src目录下创建types/leaflet-routing-machine.d.ts文件,写入以下内容:

import 'leaflet-routing-machine';

declare module 'leaflet-routing-machine' {
  interface RoutingControlOptions {
    createMarker?: (i: number, waypoint: L.Routing.Waypoint, n: number) => L.Marker | undefined;
  }
}

之后就能正常在代码中使用createMarker,并结合你的createIcon方法生成自定义标记:

this.routingControl = L.Routing.control({
  waypoints: [
    L.latLng(pickup.location.latitude, pickup.location.longitude),
    L.latLng(dropOff.location.latitude, dropOff.location.longitude),
  ],
  routeWhileDragging: true,
  createMarker: (i: number, waypoint: L.Routing.Waypoint, n: number) => {
    // 根据索引区分取货/送货点,设置对应标签
    const label = i === 0 ? 'P' : 'D';
    return L.marker(waypoint.latLng, {
      icon: this.createIcon(label)
    });
  }
}).addTo(this.mapAdmin);

方案2:使用waypointRenderer替代createMarker

如果不想修改类型定义,可采用LRM官方推荐的waypointRenderer配置项实现自定义标记:

this.routingControl = L.Routing.control({
  waypoints: [
    L.latLng(pickup.location.latitude, pickup.location.longitude),
    L.latLng(dropOff.location.latitude, dropOff.location.longitude),
  ],
  routeWhileDragging: true,
  waypointRenderer: (waypoint, index, numberOfWaypoints) => {
    const label = index === 0 ? 'P' : 'D';
    const marker = L.marker(waypoint.latLng, {
      icon: this.createIcon(label)
    });
    return marker;
  }
}).addTo(this.mapAdmin);

注意事项

  • 确保createIcon方法返回的DivIcon样式符合需求,可根据实际场景调整HTML结构和CSS样式
  • 若使用方案1,需检查tsconfig.json的include配置是否包含自定义类型文件所在的types目录

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 22:46:05