Search code examples
angulartypescriptleafletopenstreetmap

Add marker on Leaflet map from another angular component


I have declared, in my Angular application, a const map variable in my mapComponent and I am able to add custom marker on map in the same component; how can I do the same thing from other Angular components using the same map?


Solution

  • You can use a service to achieve communication between two components.

    Create a service which will hold your coords array value.

    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);
      }
    }
    

    To illustrate an example you can have in one component a button. When you click it then you call a function inside the service and change the coords array. Then in your app component for instance initialize your leaflet map. Following, subscribe to your service to get the new updated value and render the marker on the map by also changing the map view.

    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