【问题标题】:How to save geolocation details in local variables to use it later如何将地理位置详细信息保存在局部变量中以供以后使用
【发布时间】:2017-07-03 11:42:50
【问题描述】:

我对 Nativescript(使用 angular2/typescript)非常陌生。我的用例是使用 nativescript 地理定位插件跟踪用户位置并保存结果(例如纬度和经度)以供以后使用。下面是我的示例代码:

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 
}
}

但我无法将纬度和经度的值传递给 getWeather 方法。它是未定义的。我做错了什么?我知道解决方法:通过从这些值可用的 updateLocation 内部调用 getWeather 并让这个东西正常工作,但不知何故我觉得这不是一种合适的方式。提前致谢。

【问题讨论】:

  • getWeather() 函数将在 updateLocation() 方法有机会完成之前触发,因此值将是未定义的

标签: typescript geolocation nativescript angular2-nativescript


【解决方案1】:

你认为“不合适的方式”其实是合适的方式;你的 this.updateLocation() 函数是异步的(Promise),所以下面的行 (this.getWeather(this.latitude ,this.longitude)) 在 this.latitudethis.longitude 初始化之前运行。

当它们被初始化时,你会想要调用 getWeather,而这正是 Promise 在 updateLocation 中返回的时候......

【讨论】:

    猜你喜欢
    • 2011-09-05
    • 1970-01-01
    • 1970-01-01
    • 2016-11-08
    • 2011-11-07
    • 2017-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多