Ionic 5 Capacitor Android not showing geolocation results

Viewed 2857

I have an Ionic 5 / Capacitor app and I'm using geolocation.

Here is the code:

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

}

When I run it on my browser this.latitude and this.longitude shows results but when I run it on Android Studio either the emulator or the phone it shows no results at all.

How can I fix this issue as it's giving me no errors, it's just not returning any gps coordinates on my Android phone or emulator.

1 Answers

Try this:

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

I think what's happening is your browser has the location already, but on the phone you have to wait for it to get the location which is why you should use the promise returned from the getCurrentPosition() method. Also, depending on how you're using getLocation() you may also want it to return a promise when the promise returned from getCurrentPosition() has been fulfilled, otherwise this.latitude and this.longitude will likely still be null.

Related