Ionic 5 Capacitor Android 未显示地理定位结果

Ionic 5 Capacitor Android not showing geolocation results

我有一个 Ionic 5 / Capacitor 应用程序,我正在使用地理定位。

代码如下:

import { Component } from '@angular/core';
import { Geolocation } from '@capacitor/core';


@Component({
  selector: 'app-tab1',
  templateUrl: 'tab1.page.html',
  styleUrls: ['tab1.page.scss']
})
export class Tab1Page {

  latitude: number;
  longitude: number;

  constructor() {
    this.getLocation();
  }

  async getLocation() {
    const position = await Geolocation.getCurrentPosition({ enableHighAccuracy: true, timeout: 5000, maximumAge: 0 });
    this.latitude = position.coords.latitude;
    this.longitude = position.coords.longitude;
  }

}

当我 运行 它在我的浏览器上 this.latitude 和 this.longitude 显示结果但是当我 运行 它在 Android Studio 模拟器或phone 根本没有显示任何结果。

我该如何解决这个问题,因为它没有给我任何错误,它只是没有在我的 Android phone 或模拟器上返回任何 gps 坐标。

试试这个:

constructor(public geoLoc: GeoLocation){}

async getLocation() {
    const position = await this.geoLoc.getCurrentPosition({enableHighAccuracy: true, timeout: 5000, maximumAge: 0}).then(res => {
        this.latitude = res.coords.latitude;
        this.longitude = res.coords.longitude; 
    }   
});

我认为发生的事情是您的浏览器已经有了位置,但是在 phone 上您必须等待它获取位置,这就是为什么您应该使用 promise return 从 getCurrentPosition() 方法编辑。此外,根据您使用 getLocation() 的方式,当 promise return 从 getCurrentPosition() 编辑时,您可能还希望它 return a promise已经完成,否则 this.latitudethis.longitude 可能仍然是 null.