-1

I have a big problem, I'm sure I had already did that and it worked perfectly...

Here is my code :

import { Component, OnInit } from '@angular/core';
import { Map, latLng, tileLayer, Layer, marker, icon, Icon } from 'leaflet';

@Component({
  selector: 'app-map',
  templateUrl: './map.component.html',
  styleUrls: ['./map.component.scss']
})
export class MapComponent implements OnInit {

  public m : Map;
  public n : number = 3;
  public markerIcon : Icon = icon({
    iconUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.2.0/images/marker-icon.png'
  });

  constructor() { }

  ngOnInit() {

    this.initMap();

  }

  initMap(){

    console.log(this.n);

    //this.m = L.map('map').setView([44.8333, -0.5667], 5);
    this.m = new Map('map').setView([44.8333, -0.5667], 5);

    tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(this.m);
    this.m.on('click', this.addDestination);
    console.log(this.m);
  }

  addDestination(){

    console.log(this.m);

  }

}

The first console.log in "initMap" return me the instance of my map, BUT the second console.log in addDestination return me undefined.

I've did 10000000 tests. Spent too many times, please help me !

  • Issue with context of `this`. Try with an arrow function. `addDestination = () => console.log(this.m);` – SiddAjmera Dec 11 '19 at 15:12
  • Can you make a stackblitz so we can debug it? – Sam Dec 11 '19 at 15:21
  • Does this answer your question? [Javascript call() & apply() vs bind()?](https://stackoverflow.com/questions/15455009/javascript-call-apply-vs-bind) – Reactgular Dec 11 '19 at 15:30

3 Answers3

2

In your initMap method:

Change this

this.m.on('click', this.addDestination);

to:

this.m.on('click', this.addDestination.bind(this));

The issue is that when you're passing the method as a callback, the context of this is different.

Read more about this on MDN

C.OG
  • 6,236
  • 3
  • 20
  • 38
0

Use an arrow function. Instead of

  addDestination(){

    console.log(this.m);

  }

do

  addDestination = () => {
    console.log(this.m);
  }
mbojko
  • 13,503
  • 1
  • 16
  • 26
0

You can also solve this using arrow function instead of using .bind() on addDestination() method.

initMap(){

console.log(this.n);

//this.m = L.map('map').setView([44.8333, -0.5667], 5);
this.m = new L.Map('map').setView([44.8333, -0.5667], 5);

  L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(this.m);
  this.m.on('click', this.addDestination);
  console.log(this.m);
}

 addDestination=()=>{

console.log(this.m);

 }

Working demo : demo

Himanshu Singh
  • 2,117
  • 1
  • 5
  • 15