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

wz1wpwve  于 2022-12-08  发布在  Ionic
关注(0)|答案(1)|浏览(164)

我正在使用来自HERE的离子原生地理定位插件,并从提供的示例开始,所以我这样做了:

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

我不明白代码......它似乎在做同样的事情两次吗?
它包含***getCurrentPosition***和***watchPosition***部分,并且都获得了saqme数据?
怎么了,我错过什么了吗?

d8tt03nd

d8tt03nd1#

总之:**this.geolocation.getCurrentPosition()用于检索设备的当前位置一次,而this.geolocation.watchPosition()**注册一个处理函数,每次设备的位置更改时都会自动调用该函数,返回更新后的位置。
参考:https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API
代码示例:

//define the userPositionWatch
userPositionWatch: any;
//Subscriber 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);
    })

我希望你说得很清楚...

相关问题