0

I am new to the ES6. I am facing problem storing data in variable that is out of scope.I have created button event and associated getLocation() to it to find users location but I am not able to find way to update lon, lat variables which are out of scope. Bellow is the code :

lon: any;
lat: any;
getLocation() {
    var lat;
    var lon;
    navigator.geolocation.getCurrentPosition(function(d) {
        lat = d.coords.latitude.toFixed(2);
        lon = d.coords.longitude.toFixed(2);
        console.log(this.lat);
        console.log(this.lon);

    });

}
Update(lat: any, lon: any) {
    this.lat = lat;
    this.lon = lon;
}
Krupesh Kotecha
  • 2,396
  • 3
  • 21
  • 40
ANMo
  • 1
  • 1
  • 1
  • 3

1 Answers1

0
lon: any;
lat: any;
getLocation() {
    var self = this;
    navigator.geolocation.getCurrentPosition(function(d) {
        self.lat = d.coords.latitude.toFixed(2);
        self.lon = d.coords.longitude.toFixed(2);
        console.log(self.lat);
        console.log(self.lon);
    });
}

You need to leave class variables as it is and u need to just update them. when u create var lon and var lan you are creating method variables and just keeping the value within the method. Thus it will not update the class variable.

Read More: Member variables in ES6 classes

Community
  • 1
  • 1
Smit
  • 2,078
  • 2
  • 17
  • 40
  • Hii Smit. Thank you very much for answer.But can you tell me how can I access lon and lat outside getLocation().I tried but I am getting undefined. – ANMo Mar 06 '17 at 06:24
  • @ANIKETMORE Thank you for appreciation. You may select and upvote the answer. THus it can be considered closed. – Smit Mar 06 '17 at 06:25