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



我正在使用来自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数据?

为什么?我是不是错过了什么?

在summery中:this.geolocation.getCurrentPosition((用于检索设备的当前位置一次,而this.geolocation.watchPosition(([/strong>注册一个处理程序函数,该函数将在每次设备位置更改时自动调用,返回更新的位置。

参考文献: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);
})

我希望它是清楚的。。。

最新更新