My component written in typescript for a page in my Ionic2 project has the follwing structure:
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());
});
}
}
But Inside the google.maps.event.addListener(){..}
I cant reach the setPos()
declared inside my SearchPage
class. How can I call this function considering my structure?
You need to use arrow functions like this:
google.maps.event.addListener(marker, 'dragend', () => {
this.setPos(marker.getPosition().lat(),marker.getPosition().lng());
});
By using arrow functions, the this
property is not overwritten and still references the component instance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With