location unavailable capacitor ionic

Viewed 1969

location unavailable capacitor ionic.we cant access location in android device getting this error messgae.

  capacitor-runtime.js:414 {message: "location unavailable"}message: 
  "location 
  unavailable"__proto__: Object
   capacitor.logFromNative @ capacitor-runtime.js:414
   fromNative @ capacitor-runtime.js:212
    (anonymous) @ VM289:1
   pages-add-add-module-es2015.js:186 Error getting location {message: 
 "location unavailable"}
2 Answers

An android device or an emulator?

If we talk about an android device check the GPS to be enabled, for some phones is not working with this enabled.

On emulator this plugin is not working.

for Emulator, you have to set a default location first,

go to emulator settings -> Location -> Search for a place(set the marker) -> click 'Set Location'

enter image description here

Then in your component you can do something like :

import { Capacitor, Plugins } from "@capacitor/core";
const { Geolocation } = Plugins;  // don't inject in ctor()

Geolocation.getCurrentPosition({
        enableHighAccuracy: true,
      }).then((resp) => {            
        this.lat = resp.coords.latitude;
        this.lng = resp.coords.longitude;
      }).catch((error) => {
        console.log('Error getting location', error);
      });

And to check GPS permission you can use the following

isGpsPermissionEnabled(permissions: AndroidPermissions): Promise<boolean> {
    return await new Promise((resolve, reject) => {
        if (Capacitor.isNative) {
            permissions.checkPermission(permissions.PERMISSION.ACCESS_FINE_LOCATION).then(
                rs => resolve(rs.hasPermission),
                err => {
                    console.log("something went wrong")
                }
            );
        }
        else { resolve(true); // for browsers
         }
    })
}
Related