Ionic 5 Capacitor在Android上无法显示地理位置结果

3

我有一个使用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上运行它时,无论是模拟器还是手机,都没有显示任何结果。如何解决这个问题?因为它没有给我任何错误提示,只是在我的Android手机或模拟器上不返回GPS坐标。
1个回答

2
试试这个:
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; 
    }   
});

我认为问题在于你的浏览器已经有了位置信息,但是在手机上你需要等待它获取位置信息,这就是为什么你应该使用getCurrentPosition()方法返回的promise。另外,根据你如何使用getLocation(),你可能还希望它在从getCurrentPosition()返回的promise被满足时返回一个promise,否则this.latitudethis.longitude很可能仍然是null


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接