我从过去三天开始就挠头,但是一直无法达到我想要的结果,我想要的只是获取地理位置坐标,如果关闭了设备位置,则会显示提示,要求您在不离开的情况下启用该位置该应用程序和设备位置已开启我已手动对其进行了验证。但是问题是每次尝试时,我都会陷入错误方法中]
import { LocationAccuracy } from '@ionic-native/location-accuracy/ngx';
import { Plugins } from '@capacitor/core';
const { Geolocation } = Plugins;
this.locationAccuracy.request(this.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY).
then(() => {
Geolocation.getCurrentPosition({ enableHighAccuracy: true }).then(loc => {
alert('Position detected successfully' + loc);
}).catch(error => {
alert(error);
});
}).catch(deny => {
alert('You denied the location');
});
但是有一个很奇怪的东西,那就是在启动应用程序之前,如果我运行谷歌地图并找到自己的位置,那么我的应用程序可以正常工作,否则就会陷入错误方法。任何帮助将不胜感激。
页面类(
已更新错误处理):
import { Component } from '@angular/core';
import { GeolocationPosition, Plugins } from '@capacitor/core';
const { Geolocation } = Plugins;
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
currentPos: GeolocationPosition;
waitingForCurrentPosition = false;
constructor() {
}
async getCurrentPos() {
try {
this.waitingForCurrentPosition = true;
this.currentPos = await Geolocation.getCurrentPosition();
console.log(this.currentPos);
} catch (err) {
console.error('Failed to get current position.', err);
} finally {
this.waitingForCurrentPosition = false;
}
}
}
页面模板:
<ion-header> <ion-toolbar> <ion-title> Capacitor Geolocation </ion-title> </ion-toolbar> </ion-header> <ion-content> <ion-button (click)="getCurrentPos()" expand="block"> <ion-spinner *ngIf="waitingForCurrentPosition"></ion-spinner> Get Current position </ion-button> <ul *ngIf="currentPos"> <li>timestamp: {{ currentPos.timestamp }}</li> <li>coords: <ul> <li>latitude: {{ currentPos.coords.latitude }}</li> <li>longitude: {{ currentPos.coords.longitude }}</li> <li>accuracy: {{ currentPos.coords.accuracy }}</li> <li>altitudeAccuracy: {{ currentPos.coords.altitudeAccuracy }}</li> <li>altitude: {{ currentPos.coords.altitude }}</li> <li>speed: {{ currentPos.coords.speed }}</li> <li>heading: {{ currentPos.coords.heading }}</li> </ul> </li> </ul> </ion-content>
[当您尝试获取职位时,该应用程序将请求权限(单击按钮)。这可在2个测试设备上使用:
我创建了一个basic demo in this repo。