0

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.

1 Answer 1

1

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.
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. how small was a issue haha. thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.