Geolocation +ionic + android

I am trying to get my current location in ionic2 with the following code:

  Geolocation.getCurrentPosition() .then((resp) => {
     let position = new google.maps.LatLng(resp.coords.latitude, resp.coords.longitude);
     ...
   })  .catch((error)=>{
        console.log(error)
   })

However android studio gives me the following error when running on android device:

E/cr_LocationProvider: Caught security exception while registering for location updates from the system. The application does not have sufficient geolocation permissions.

If I hard code the coordinates, the map works!

Anyone had the same issue?

edit:
I have the following in my android manifest:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="org.apache.cordova" android:versionName="1.0" android:versionCode="1">
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-sdk android:minSdkVersion="14" />
</manifest>

And config.xml ( The line with two start from both sides gives an error and is in red (URI is not registered))

<?xml version='1.0' encoding='utf-8'?>
**<widget id="com.ionicframework.uber974736" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">**
    <feature name="Device">
        <param name="android-package" value="org.apache.cordova.device.Device" />
    </feature>
    <feature name="SplashScreen">
        <param name="android-package" value="org.apache.cordova.splashscreen.SplashScreen" />
        <param name="onload" value="true" />
    </feature>
    <feature name="StatusBar">
        <param name="android-package" value="org.apache.cordova.statusbar.StatusBar" />
        <param name="onload" value="true" />
    </feature>
    <feature name="Whitelist">
        <param name="android-package" value="org.apache.cordova.whitelist.WhitelistPlugin" />
        <param name="onload" value="true" />
    </feature>
    <feature name="Keyboard">
        <param name="android-package" value="io.ionic.keyboard.IonicKeyboard" />
        <param name="onload" value="true" />
    </feature>
    <name>uber</name>
    <description>An awesome Ionic/Cordova app.</description>
    <author email="hi@ionicframework" href="http://ionicframework.com/">Ionic Framework Team</author>
    <content src="index.html" />
    <access origin="*" />
    <allow-navigation href="http://ionic.local/*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <allow-intent href="market:*" />
    <preference name="loglevel" value="DEBUG" />
    <preference name="webviewbounce" value="false" />
    <preference name="UIWebViewBounce" value="false" />
    <preference name="DisallowOverscroll" value="true" />
    <preference name="android-minSdkVersion" value="16" />
    <preference name="BackupWebStorage" value="none" />
    <preference name="SplashMaintainAspectRatio" value="true" />
    <preference name="FadeSplashScreenDuration" value="300" />
    <preference name="SplashShowOnlyFirstTime" value="false" />
</widget>

In my index.html (this should not be a problem since I used the same script src to test without geolocation and it worked)
<script src="https://maps.googleapis.com/maps/api/js?key=MY_REAL_KEY&libraries=places,DirectionsService,DirectionsRenderer,Geocoder"></script>

You should not need to add these values yourself. The plugin actually will do this for you.

Quick sanity check, run this

ionic platform rm android
ionic platform add android@latest

Chances are what happened is you installed an older version of cordova-android, which did not have the changes needed for geolocation permissions. I have tested out the latest release and it seems to work fine.

1 Like

Thank you! It works!

I have make this, add Geolocation in app.module.ts providers, add this geolocation code on platform ready like this:

  ngAfterViewInit() {
    this.platform.ready().then(() => {
      this.openHome();
      this.setGeolocation();
      // this.initOneSignal();
    });
  }

  setGeolocation() {
    this.geolocation.getCurrentPosition()
      .then(res => console.log(res))
      .catch(err => console.error(err));
  }

and I still get this error: application does not have sufficient geolocation permissions.

this is the error menssage:

ionic info:

cli packages: (/usr/local/lib/node_modules)

    @ionic/cli-plugin-proxy : 1.5.5
    @ionic/cli-utils        : 1.19.0
    ionic (Ionic CLI)       : 3.19.0

global packages:

    cordova (Cordova CLI) : 6.5.0 

local packages:

    @ionic/app-scripts : 2.0.2
    Cordova Platforms  : android 6.1.2 ios 4.3.1 windows 4.4.3
    Ionic Framework    : ionic-angular 3.5.3

System:

    Android SDK Tools : 25.2.3
    Node              : v6.11.2
    npm               : 5.3.0 
    OS                : macOS High Sierra
    Xcode             : Xcode 9.2 Build version 9C40b 

Environment Variables:

    ANDROID_HOME     : /Users/ronaiza.cardoso/Library/Android/sdk
    HTTP_PROXY       : not set
    http_proxy       : not set
    HTTPS_PROXY      : not set
    https_proxy      : not set
    IONIC_HTTP_PROXY : not set
    PROXY            : not set
    proxy            : not set

Misc:

    backend : pro

I had to update the cordova version to 6.3.0 with this command:

 cordova platform update android@6.3.0

this worked.

but sir i am using android 6.4.0 version why got initially but 2nd time not get above error?

i tried but not error after run android?

The error you’re encountering seems to be related to insufficient geolocation permissions in your Android application. You’ve declared the necessary permissions in your AndroidManifest.xml file, which is a good start. However, you should also ensure that you have requested runtime permissions in your Ionic application because Android requires explicit user consent for location access.

To request runtime permissions in an Ionic application, you can use the Cordova plugin ``cordova-plugin-android-permissions. Here’s how you can do it:

1. Install the plugin:

ionic cordova plugin add cordova-plugin-android-permissions

  1. Request location permissions in your code before attempting to use the Geolocation API. You can add this code to your Ionic component where you want to use geolocation:
import { AndroidPermissions } from '@ionic-native/android-permissions/ngx';

constructor(private androidPermissions: AndroidPermissions) {}

requestLocationPermission() {
  this.androidPermissions.requestPermissions([
    this.androidPermissions.PERMISSION.ACCESS_FINE_LOCATION,
    this.androidPermissions.PERMISSION.ACCESS_COARSE_LOCATION
  ]).then((result) => {
    if (result.hasPermission) {
      // You have permission; you can now use Geolocation.getCurrentPosition()
    } else {
      console.error('Location permission denied');
    }
  }).catch((error) => {
    console.error('Error requesting location permission', error);
  });
}

getLocation() {
  this.requestLocationPermission();

  Geolocation.getCurrentPosition().then((resp) => {
    let position = new google.maps.LatLng(resp.coords.latitude, resp.coords.longitude);
    // ... your code here
  }).catch((error) => {
    console.log(error);
  });
}

In this code, we first import the AndroidPermissions plugin, then request the required location permissions using requestPermissions(). If the user grants the permissions, you can proceed with Geolocation.getCurrentPosition().

Remember to call the getLocation() function when you want to retrieve the user’s location.

Also, make sure you have imported the AndroidPermissions module in your app module (app.module.ts) and added it to the providers array. This enables the injection of the AndroidPermissions service.

After implementing these changes, your Ionic application should properly request and handle location permissions on Android devices, allowing you to use the Geolocation API without issues.

I tried this on my location and it seems to be working fine

Thanks, for me : Android 33 adding permission do androidManifest.xml works well, why do you need this extra step ?

My only problem using capacitor geolocation, is the watch method… which is very slow in acquiring the coordinates, and there is no parameter to tweak it.
I need near real-time tracking of the device…like google maps, but I’m using leaflet.

I improve the acquisition rate, by changing the code of the plugin geolocation, but it’s some sort of a hack… I need a bulletproof solution.

Anybody with this problem ?