我正在使用 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
});
}
我不明白代码...它似乎在做同样的事情两次吗?
它有 getCurrentPosition 和 watchPosition 部分并且都获取 saqme 数据?
为什么?我是不是漏掉了什么?
总之: 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);
})
我希望这是清楚的...