Leaflet locationfound在映射准备就绪之前触发

Leaflet locationfound在映射准备就绪之前触发,leaflet,Leaflet,因此,我正在遵循关于mobile传单地图的传单文档示例,但我对onlocationfound事件有一个问题 它被触发了,但是当我从函数调用map时,它是未定义的。我把它用在角上 export class MapComponent implements OnInit { myMap: L.map; constructor() { } ngOnInit(): void { this.myMap = new L.map("myMap").fitWorld(); le

因此,我正在遵循关于mobile传单地图的传单文档示例,但我对onlocationfound事件有一个问题

它被触发了,但是当我从函数调用map时,它是未定义的。我把它用在角上

export class MapComponent implements OnInit {

  myMap: L.map;

  constructor() { }

  ngOnInit(): void {
    this.myMap = new L.map("myMap").fitWorld();

    let oMap = new L.tileLayer('http://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}', {
      maxZoom: 21,
      subdomains: ['mt0', 'mt1', 'mt2', 'mt3'],
      attribution: 'Tiles © Google Maps'
    });
    oMap.addTo(this.myMap);

    this.myMap.locate({ setView: true, zoom: 16 });

    this.myMap.on('locationerror', this.onLocationError);
    this.myMap.on('locationfound', this.onLocationFound);

  }


  onLocationFound(e) {
    console.log(this.myMap);
    let radius = e.accuracy;

    L.marker(e.latlng).addTo(this.myMap)
      .bindPopup("You are within " + radius + " meters from this point").openPopup();

    L.circle(e.latlng, radius).addTo(this.myMap);

  }

  onLocationError(e) {
    alert(e.message);
  }
}
我不确定我做错了什么

错误是:

core.js:5871 ERROR TypeError: Cannot read property 'addLayer' of undefined
    at NewClass.addTo (leaflet-src.js:6559)
    at NewClass.onLocationFound (map.component.ts:42)
    at NewClass.fire (leaflet-src.js:593)
    at NewClass._handleGeolocationResponse (leaflet-src.js:3742)
    at ZoneDelegate.invoke (zone-evergreen.js:365)
    at Object.onInvoke (core.js:41271)
    at ZoneDelegate.invoke (zone-evergreen.js:364)
    at Zone.runGuarded (zone-evergreen.js:134)
    at zone-evergreen.js:118

而这个.myMap在控制台上显示为未定义。

这不是竞争条件,而是范围问题。将
console.log(this)
放入
onLocationFound()
中,准备好惊讶。然后,阅读关于Thank的文章,看到错误时会感到困惑,但现在我通过调用函数以另一种方式使其正常工作;)我以前读过这方面的文章,但我还不习惯。