从另一个 angular 组件在 Leaflet 地图上添加标记

Add marker on Leaflet map from another angular component

我已经在我的 Angular 应用程序中声明了我的 mapComponent 中的常量地图变量,并且我能够在同一组件的地图上添加自定义标记;我怎样才能使用同一张地图从其他 Angular 组件做同样的事情?

您可以使用服务来实现两个组件之间的通信。

创建一个服务来保存您的坐标数组值。

class MarkerService {
  coords: any;
  coordsChange: Subject<LatLngExpression> = new Subject<LatLngExpression>();

  constructor() {
    this.coords = [];
  }

  change(coords: Array<number>) {
    this.coords = coords;
    this.coordsChange.next(this.coords);
  }
}

为了举例说明,您可以在一个组件中包含一个按钮。当您单击它时,您将调用服务内部的一个函数并更改坐标数组。 然后在您的应用程序组件中初始化您的传单地图。接下来,订阅您的服务以获取新的更新值并通过更改地图视图在地图上呈现标记。

map;

  constructor(private ms: MarkerService) {
    console.log(this.ms.coords);
    this.ms.coordsChange.subscribe(coords => {
      console.log(coords);
      this.map.flyTo(coords, this.map.getZoom());
      L.marker(coords, { icon }).addTo(this.map);
    });
  }

Demo