0

I am trying to bind a value from this on click event in a leaflet js map on angular 4. But, it doesnt give acces to the binded variables. I want to update those bound variables on click event. Please help me to find a way to access those bound values.

export class ViewLocationsComponent implements OnInit {

 long = '';
  lati = '';//These values needed to be accessed
 ngOnInit() {
    this.loadAllLocations();
    this.update();
  }

update(): void{
    const map = L.map('map').setView([51.505, -0.09], 13);
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map);

    map.on('click', function (e){

      var lati = e.latlng.lat;
      var long = e.latlng.lng;//These are the values needed to be bind
      alert(lati+"  "+long);
       var marker = new L.marker([e.latlng.lat,e.latlng.lng]).addTo(map);

      marker.bindPopup("marker").openPopup();

    });

  }

}

It does not support 'this' keyword inside this function.

  • Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – user184994 Nov 05 '18 at 16:20

1 Answers1

0

I doubt whether I understood your question correctly. But I think maybe this what you are looking for.

export class ViewLocationsComponent implements OnInit {

    long = 0;   lati = 0; //These values needed to be accessed  ngOnInit() {
    this.loadAllLocations();
    this.update();   }

update(): void{
    const map = L.map('map').setView([51.505, -0.09], 13);
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
    }).addTo(map);

    map.on('click', e=>{

      this.lati = e.latlng.lat;
      this.long = e.latlng.lng;//These are the values needed to be bind
      alert(lati+"  "+long);
       var marker = new L.marker([e.latlng.lat,e.latlng.lng]).addTo(map);

      marker.bindPopup("marker").openPopup();

    });

  }

}
Ranjith Suranga
  • 316
  • 1
  • 10