Reputation: 138
I have this Ionic 2 typescript file. I am trying to set value of a variable from another method. I received undefined on closing the modal.
not able to set the value for coord below.
export class RegisterMapPage {
.. essential var here..
public coord: any;
constructor(
....
) {}
ionViewDidLoad() {
this.initMap()
}
initMap() {
this.geolocation.getCurrentPosition().then((position) => {
// // // ..... All map related code here....
google.maps.event.addListener(marker, 'dragend', function () {
this.coord = marker.getPosition().lat() + ', ' + marker.getPosition().lng();
console.log(this.coord); // prints perfectly here.
});
}, (err) => {
console.log(err);
});
}
chooseCoord() {
console.log(this.coord); // undefined ??
this.viewCtrl.dismiss(this.coords);
}
}
On marker drag event I update the variable value or coord but the value is undefined when I print it. Can you please help me with the code.
Thanks.
Upvotes: 0
Views: 175
Reputation: 40672
Because the this
inside your callback method is not RegisterMapPage
instance since you are using the function() {}
syntax for the callback. Use arrow function to get the correct context:
google.maps.event.addListener(marker, 'dragend', () => {
this.coord = marker.getPosition().lat() + ', ' + marker.getPosition().lng(); // `this` here will point to `RegisterMapPage` instance now that you use arrow function
console.log(this.coord); // prints perfectly here.
});
Upvotes: 1