0

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?

2
  • Do you want to add a marker in your map which is lets say in component 1 from a different component, f.i component 2?
    – kboul
    Commented Feb 11, 2020 at 9:09
  • @kboul Yes, I have Component_1 in which I've declared the map using leaflet, and Component_2 that stores a coordinate in lat long format, I would make something like this in Component_2: Component_1.addMarker(Component_2.localCoordinatesVariable)
    – GDC
    Commented Feb 11, 2020 at 9:21

1 Answer 1

1

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.