1

I am trying to implement Leaflet in my angular 7 project i try to google the solution but nothing all the result is for angularjs or vanilla javascript.

This is my ts file:

 ngAfterViewInit(): void {
    //Init map & add tile
    this.map = new Map('map').setView([25.1220946, 56.3342466], 13);
    tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}').addTo(this.map);
    //onClick
    this.map.on("click", function(e){
    //Add marker
    this.myMarker = marker([e.latlng.lat, e.latlng.lng]).addTo(this.map);
    // console.log();
      console.log(`Your lat is : ${e.latlng.lat} and your lang :  ${e.latlng.lng}`);
    });
  }

FYI it's not duplicate, the same question is 5 years old everything is different now.

kboul
  • 13,836
  • 5
  • 42
  • 53
Nadim
  • 280
  • 2
  • 12

2 Answers2

4

To add a marker on map click you need to listen to a map click event once your map object is instantiated:

ngOnInit() {
    this.map = L.map("map").setView([25.1220946, 56.3342466], 13);
    L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
      attribution:
        '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(this.map);

    this.map.on("click", e => {
      console.log(e.latlng); // get the coordinates
      L.marker([e.latlng.lat, e.latlng.lng], this.markerIcon).addTo(this.map); // add the marker onclick
    });
  }

Here is an example using Angular 8: Demo

kboul
  • 13,836
  • 5
  • 42
  • 53
0

As per @kboul answer we can achieve that (Add a new marker each time i click on the map with the right lat lng) with this lines of code :

ngAfterViewInit(): void {
    //Init map & add tile
    this.map = new Map('map').setView([25.1220946, 56.3342466], 13);
    tileLayer('http://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}').addTo(this.map);
    //onClick
    this.map.on("click", e => {
      console.log(e.latlng); // get the coordinates
      if (this.myMarker) { // check
        this.map.removeLayer(this.myMarker); // remove
    } this.myMarker = new marker([e.latlng.lat, e.latlng.lng]).addTo(this.map); // add the marker onclick
    });
  }
Nadim
  • 280
  • 2
  • 12