首页 > 解决方案 > 离子地理定位总是陷入错误方法

问题描述

我一直未能达到我想要的结果。我想要的只是获取地理位置坐标,如果设备位置已关闭,则会显示提示以在不离开应用程序的情况下启用该位置,并且设备位置已打开,我已手动验证。

但问题是每次我尝试时,我都会陷入错误方法

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

    });

但是有一些非常奇怪的事情,那就是在启动应用程序之前,如果我运行谷歌地图并定位自己,那么我的应用程序可以正常运行,否则它会一直陷入错误方法。

标签: androidangularionic-frameworkgeolocationgps

解决方案


我认为您不需要cordova-plugin-request-location-accuracy。以下是使用 Capacitor 获取当前位置的方法:

页面类(更新错误处理):

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 个测试设备:

  • 一加 6(安卓 10)
  • BlackView A60 (Android Go)

我之前在 iPhone 6S 上测试过它,所以它也应该适用于 iOS。

在这个 repo 中创建了一个基本的演示


推荐阅读