从 google.maps.event.listener 调用我的函数
Call my function from the google.maps.event.listener
我在 Ionic2 项目中用打字稿为页面编写的组件具有以下结构:
import { Component, ViewChild, ElementRef } from '@angular/core';
...
declare var google;
@Component({
selector: 'page-search',
templateUrl: 'search.html'
})
export class SearchPage {
@ViewChild('map') mapElement: ElementRef;
map: any;
guideList: Array<Guide>;
text: any;
lat : any;
lon : any;
constructor(public navCtrl: NavController, public recoshService: Recosh, public alertCtrl: AlertController) {
...
}
ngOnInit(){
this.loadMap();
}
loadGuides() {
...
}
setLat(l){
this.recoshService.setLat(l);
this.lat = l;
}
setLon(l){
this.recoshService.setLon(l);
this.lon = l;
}
setPos(lat, lon){
this.setLon(lon);
this.setLat(lat);
this.loadGuides();
}
loadMap(){
...
let marker = new google.maps.Marker({
position: this.map.getCenter(),
icon: {
path: google.maps.SymbolPath.BACKWARD_CLOSED_ARROW,
scale: 5,
strokeWeight:2,
strokeColor:"#B40404"
},
draggable:true,
map: this.map,
});
google.maps.event.addListener(marker, 'dragend', function() {
this.setPos(marker.getPosition().lat(),marker.getPosition().lng());
});
}
}
但是在 google.maps.event.addListener(){..}
中,我无法访问在 SearchPage
class 中声明的 setPos()
。考虑到我的结构,我该如何调用这个函数?
你需要像这样使用箭头函数:
google.maps.event.addListener(marker, 'dragend', () => {
this.setPos(marker.getPosition().lat(),marker.getPosition().lng());
});
通过使用箭头函数,this
属性 不会被覆盖并且仍然引用组件实例。
我在 Ionic2 项目中用打字稿为页面编写的组件具有以下结构:
import { Component, ViewChild, ElementRef } from '@angular/core';
...
declare var google;
@Component({
selector: 'page-search',
templateUrl: 'search.html'
})
export class SearchPage {
@ViewChild('map') mapElement: ElementRef;
map: any;
guideList: Array<Guide>;
text: any;
lat : any;
lon : any;
constructor(public navCtrl: NavController, public recoshService: Recosh, public alertCtrl: AlertController) {
...
}
ngOnInit(){
this.loadMap();
}
loadGuides() {
...
}
setLat(l){
this.recoshService.setLat(l);
this.lat = l;
}
setLon(l){
this.recoshService.setLon(l);
this.lon = l;
}
setPos(lat, lon){
this.setLon(lon);
this.setLat(lat);
this.loadGuides();
}
loadMap(){
...
let marker = new google.maps.Marker({
position: this.map.getCenter(),
icon: {
path: google.maps.SymbolPath.BACKWARD_CLOSED_ARROW,
scale: 5,
strokeWeight:2,
strokeColor:"#B40404"
},
draggable:true,
map: this.map,
});
google.maps.event.addListener(marker, 'dragend', function() {
this.setPos(marker.getPosition().lat(),marker.getPosition().lng());
});
}
}
但是在 google.maps.event.addListener(){..}
中,我无法访问在 SearchPage
class 中声明的 setPos()
。考虑到我的结构,我该如何调用这个函数?
你需要像这样使用箭头函数:
google.maps.event.addListener(marker, 'dragend', () => {
this.setPos(marker.getPosition().lat(),marker.getPosition().lng());
});
通过使用箭头函数,this
属性 不会被覆盖并且仍然引用组件实例。