Search code examples
typescriptgeolocationnativescriptangular2-nativescript

How to save geolocation details in local variables to use it later


I am pretty noob to Nativescript (with anngular2/typescript). My use case is to track users location using nativescript geolocation plugin and save the results (such as latitude and longitude) for the later usage. Below is my sample code :

export class AppComponent {
    public latitude: number;
    public longitude: number;

 public constructor() 
 {
      this.updateLocation();
      this.getWeather(this.latitude ,this.longitude);
 }

private getDeviceLocation(): Promise<any> {
        return new Promise((resolve, reject) => {
            geolocation.enableLocationRequest().then(() => {
                geolocation.getCurrentLocation({desiredAccuracy:3,updateDistance:10,timeout: 20000}).then(location => {
                    resolve(location);

                }).catch(error => {
                    reject(error);
                });
            });
        });
    }

 public updateLocation() {
        this.getDeviceLocation().then(result => {
// i am saving data here for later usage 
            this.latitude = result.latitude;
            this.longitude = result.longitude;
        }, error => {
            console.error(error);
        });
    }

public getWeather(latitude:number,longitude:number){
// do stuff with lat and long 
}
}

But i am not able to pass the value of latitude and longitude to getWeather method.It comes as undefined.What i am doing wrong? I know the workaround : by calling getWeather right inside from updateLocation where these values are available and get this thing working but somehow I feel it is not an appropriate way.Thanks in advance.


Solution

  • What you think is "not an appropriate way" is actually the appropriate way; your this.updateLocation() function is async (Promise), so the line below (this.getWeather(this.latitude ,this.longitude)) runs before this.latitude and this.longitude are initialized.

    You'll want to invoke getWeather when those are initialized, and that's exactly when the Promise returns in updateLocation..