获取未定义,了解这一点,事件,离子,谷歌地图和Firebase

时间:2017-03-22 08:01:59

标签: javascript ionic-framework maps geofire

我有一些独立工作的代码,但是当我把它放在一起时,我在“this”处出现“Undefined”错误 由于我缺乏对JS的理解,这有点令人沮丧。 我让它在Ionic 1中工作,但不在Ionic 2中工作。 我有两个事件,来自地图的“MAP_READY”和来自Geofire的“key_entered”。 我非常感谢你的指导。以下是代码的基本部分:

platform.ready().then(() => {
 this.LOADMAP();
});
//---------Loading map ----------
LOADMAP(){
 Geolocation.getCurrentPosition().then((position) => {
 this.map = new GoogleMap('map', {
  'backgroundColor': 'white',
  'controls':....
...
...
 }
 this.map.on(GoogleMapsEvent.MAP_READY).subscribe(() => {
 this.GETMARKERS();
}, 
 (err) => {
 console.log(err);
 });
 });
}

//-----Get markers from Geofire/Firebase
GETMARKERS(){
...
...
 var geoQuery = geoFire.query({
  center: [lat,lon],
  radius: 3000
 });
...

var onKeyEnteredRegistration=GeoQuery.on("key_entered",
  function(key,location) {
 this.ADDMARKER(location)
  });
  }
}

//-------Adding marker to map
ADDMARKER(location){
 let markerOptions: GoogleMapsMarkerOptions = 
  {position: location,title:'Some title' };

 this.map.addMarker(markerOptions) <-------------------- This gives error 
 .then((marker: GoogleMapsMarker) => {
  marker.showInfoWindow();
 });
}

1 个答案:

答案 0 :(得分:0)

错误可能会在此处显示

this.map.addMarker(markerOptions) 

但实际错误在

var onKeyEnteredRegistration=GeoQuery.on("key_entered",
  function(key,location) { <---------- HERE
 this.ADDMARKER(location)
  });
  }
}

将您的代码更改为

var onKeyEnteredRegistration=GeoQuery.on("key_entered",
 (key,location) =>{
    this.ADDMARKER(location)
  });
  }
}

'function'将改变范围,这就是为什么'this'不会在块内工作。 希望这可以帮助! :)