如何将 Fused Location API 与电容器一起使用? - 离子 5

How to use Fused Location API with capacitor ? - Ionic 5

我正在构建一个带电容器的离子应用程序。目前我 运行 在需要使用 GPS 获取用户位置的用例中。

在挖掘了将近 2 小时后,我发现融合位置是可行的方法。

从电容器的官方文档中我找不到有关如何调用融合位置来获取 android 上的地理位置的相关信息。 以下是在浏览器上运行但在设备上运行失败的测试代码。

import { Geolocation } from '@capacitor/core'; 
 
export class HomePage implements OnInit {

 latitude: number;
 longitude: number;

 constructor() {}

  async getCurrentPosition() {
    const coordinates = await Geolocation.getCurrentPosition();
    console.log('Current', coordinates);
  }

  watchPosition() {
    Geolocation.watchPosition({}, (position, err) => {
        this.latitude = position.coords.latitude;
        this.longitude = position.coords.longitude
        console.log(position);
    })
  }
}

如果您没有在模板中看到位置,您可能需要 运行 NgZone 内的回调:

import { Component, NgZone } from '@angular/core';

// ...

constructor(
    private ngZone: NgZone,
) { }

watchPosition() {
    this.locationWatchId = Geolocation.watchPosition(this.geolocationOptions, (position, err) => {
        this.ngZone.run(() => {
            if (err) {
                console.error('Failed to watch position.', err);
            }

            this.latitude = position.coords.latitude;
            this.longitude = position.coords.longitude
            console.log(position);
        });
    });
}