Ionic Native Geolocation 示例不理解描述演示代码

问题描述 投票:0回答:1

我正在使用 HERE 中的 Ionic Native Geolocation 插件,并从提供的示例开始,所以我这样做了:

getLocation() {

  this.geolocation.getCurrentPosition().then((resp) => {
    // resp.coords.latitude
    // resp.coords.longitude
  }).catch((error) => {
    console.log('Error getting location', error);
  });

  let watch = this.geolocation.watchPosition();
  watch.subscribe((data) => {
    // data.coords.latitude
    // data.coords.longitude
  });
}

我不明白代码...它似乎在做同样的事情两次吗?

它有 getCurrentPositionwatchPosition 部分并且都获取 saqme 数据?

为什么?我是不是漏掉了什么?

ionic-framework ionic-native
1个回答
0
投票

总之: this.geolocation.getCurrentPosition() 用于检索设备的当前位置一次,而 this.geolocation.watchPosition() 注册一个处理函数,每次设备位置发生变化时都会自动调用该函数,返回更新后的位置。

参考资料: https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API

代码示例:

//define the userPositionWatch
userPositionWatch: any;

//Subscribe to the userPositionWatch
this.userPositionWatch = this.geolocation.watchPosition()
    .subscribe(
        (position: any) => {
            // This method will be triggered each time the position of the device changes
            console.debug("geolocation.watchPosition => the callback function have been triggered");
            let data: any = position;
            if (data.coords !== undefined) {
                this.doSomethingWithThePos(data.coords.latitude, data.coords.longitude);
            } else {
                console.error("geolocation.watchPosition() => the callback function have been triggered and the position is undefined", data);
            }
        }
        , (error: any) => {
            console.error("geolocation.watchPosition() => the callback function have been triggered and the there is an error:", error);
        });

//To remove the subscription 
this.userPositionWatch.unsubscribe();
//Another way to remove the subscription
navigator.geolocation.clearWatch(this.userPositionWatch);
    
    
this.geolocation.getCurrentPosition()
    .then((position: any) => {
        let data: any = position;
        if (data.coords !== undefined) {
            this.doSomethingWithThePos(data.coords.latitude, data.coords.longitude);
        } else {
            console.error("geolocation.getCurrentPosition() => the position is undefined", data);
        }
    }).catch(error => {
        console.error("geolocation.getCurrentPosition() => the position has error:", error);
    })

我希望这是清楚的...

© www.soinside.com 2019 - 2024. All rights reserved.