Search code examples
ionic-frameworkngcordova

Ionic app doesn't ask permission to access location while installing


I've followed the following steps to create an app:

ionic start ionic-maps blank
cd ionic-maps
ionic setup sass
ionic io init
ionic platform add android
bower install ngCordova

Added the following lines to index.html:

<script src="lib/ngCordova/dist/ng-cordova.js"></script>
<script src="cordova.js"></script>

Changed app.js to include ngCordova:

angular.module('starter', ['ionic', 'starter.controllers', 'ngCordova'])

Installed the geolocation plugin:

cordova plugin add cordova-plugin-geolocation

app.js:

.state('app.location', {
  url: '/location',
  views: {
    'menuContent': {
      templateUrl: 'templates/location.html',
      controller: 'LocationCtrl'
    }
  }
})

location.html:

<ion-view view-title="Search">
  <ion-content>
    <h1>Location: {{location}}</h1>
  </ion-content>
</ion-view>

controllers.js:

.controller('LocationCtrl', function($scope, $state, $cordovaGeolocation) {
  $scope.location = 'Waiting';

  var options = {timeout: 10000, enableHighAccuracy: true};
  $cordovaGeolocation.getCurrentPosition(options).then(function(position) {
    var lat = position.coords.latitude;
    var lng = position.coords.longitude;
    console.log(lat, lng);
    $scope.location = lat + ' ' + lng;
  }, function(error) {
    console.log('Could not get location: ', error);
    $scope.location = 'Could not get location: ' + error + ' :: ' + JSON.stringify(error);
  });
})

If I open the /location endpoint in my phone's browser (using ionic serve) I'm shown my current location correctly. So far everything works as expected.

/platforms/android/AndroidManifest.xml has the following lines in it:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

I'm building the app using the new cloud package builder using ionic package build android. ionic package list shows that the build was successful.

I expected that I'll be asked for location permission while installing the app from apk. But I'm only asked for full network access. On visiting the /locations screen I get an error [object PositionError. json.stringify(error) is {} and Object.keys(error).length is 0.

Using navigator.geolocation.getCurrentPosition instead of $cordovaGeolocation.getCurrentPosition doesn't help.

alert(error.code) is 2 and alert(error.message) is application does not have sufficient geolocation permisions.

PS: I've ensured that GPS is enabled and it works on other apps.


Solution

  • Run cordova plugin add cordova-plugin-geolocation with --save option i.e. cordova plugin add cordova-plugin-geolocation --save so that the plugin gets added to config.xml.

    Alt: adding "cordova-plugin-geolocation" to "cordovaPlugins" in package.json also solves the issue but has been deprecated.