简体   繁体   中英

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

I'm building an ionic app with capacitor. Currently i'm running in a use case where I need to use GPS to get user location.

After digging out for almost 2hrs, I found out that fused location is the way to go.

From capacitor official documents I couldn't find relevant info on how to call fused location to get geo location on android. Below is the tested code that runs on browsers but fails on device.

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

If you don't see the position in the template you probably need to run the callback inside the 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);
        });
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM