issue with cordova-plugin-geolocation functionality on Android mobile device

Having trouble with the cordova-plugin-geolocation plugin in my ionic/cordova app. It functions perfectly on my browser and iOS device, but when I try it on Android, the map fails to display and does not acquire GPS coordinates. Instead, it times out and throws an error message:

[object PositionError]

I first added the necessary plugins using the following commands in the CLI:

cordova plugin add cordova-plugin-geolocation
cordova plugin add cordova-plugin-whitelist

Then included the following scripts in my index.html file:

<script src="//maps.googleapis.com/maps/api/js"></script>
<script src="lib/angular-google-maps/dist/angular-google-maps.min.js"></script>

Modified my app.js file to include 'uiGmapgoogle-maps':

var app = angular.module('myApp', ['ionic', 'ngCordova', 'uiGmapgoogle-maps']);

The HTML code for the map section:

 <!-- Google map -->
    <ui-gmap-google-map center='map.center' zoom='map.zoom'>
      <ui-gmap-marker coords="marker.coords" options="marker.options" events="marker.events" idkey="marker.id" closeClick="hideMarkerPopup()" onClicked="showMarkerPopup()"></ui-gmap-marker>
    </ui-gmap-google-map>

Finally, the logic in the controller section:

ionic.Platform.ready(function() {

            var posOptions = {
                enableHighAccuracy: true,
                timeout: 20000,
                maximumAge: 0
            };

            // Display 'loading' dialog
            $ionicLoading.show({
                template: 'Loading...'
            });

            $cordovaGeolocation.getCurrentPosition(posOptions).then(function(position) {

                // Update map data
                $scope.location = {};
                $scope.location.lat = position.coords.latitude;
                $scope.location.long = position.coords.longitude;
                $scope.map = {
                    center: {
                        latitude: $scope.location.lat,
                        longitude: $scope.location.long
                    },
                    zoom: 16,
                    pan: 1
                };

                $scope.marker = {
                    id: 0,
                    coords: {
                        latitude: $scope.location.lat,
                        longitude: $scope.location.long
                    }
                };

                $scope.marker.options = {
                    draggable: false
                };

                // Dismiss 'loading' dialog
                $ionicLoading.hide();

            }, function(err) {

                // Dismiss 'please wait' dialog
                $ionicLoading.hide();

                var alertPopup = $ionicPopup.alert({
                    title: 'GPS Error',
                    template: err
                });

            });

        }); // ionic.Platform.ready END

Works fine on browser and iOS, but not on Android devices. Any suggestions?

Answer №1

Ensuring the accuracy of geoLocation for every scenario proved to be a challenge, so I resorted to utilizing an external service as a backup in case cordovaGeoLocation encounters any errors:

  /** declaring the use of an external service */

  $scope.getLocation = function (){
    return $http.get("http://ip-api.com/json/" ,{
      headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    }
    }).catch(function(error) {
      console.log(error);
    });
  }

 /** implementing the external service */

$scope.getLocation().then(function (res){
        var coords = {
          Coordinates : {
            latitude: res.data.lat
            ,longitude: res.data.lon
          }
        };
        $scope.coords = coords.Coordinates;
      }).catch(function (err){
        console.log(err);
      });

Answer №2

When I faced the same issue, I found that the solution was to include the following lines in the AndroidManifest.xml file (which can be found in Platforms -> Android):

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

It seems like the plugin forgot to add these permissions to the manifest file.

Answer №3

After encountering the same issue as many others, I took it upon myself to share the solution for those struggling to find information on how to resolve it. Thanks to a helpful tutorial I found at , I discovered that installing the whitelist plugin and correctly using a specific meta tag in the index.html file was the key to success (details can be found in the tutorial). This fix has worked flawlessly on Android devices for me.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Phonegap alongside ons-scroller and ons-button

Recently, I have been using Phonegap with the Onsen UI system on iOS devices. I encountered an issue where buttons included within an ons-scroller were not clickable when running on an iPad or iPhone. Here is the code snippet that caused the problem: < ...

Troubleshooting Issue with Ionic's UI Router

Recently, I created a basic Ionic app to gain a better understanding of UI router functionality. To my surprise, when I ran the app, nothing appeared on the screen. Additionally, the developer tools in Google Chrome did not show any errors or information. ...

The bootstrap navbar dropdown feature isn't functioning properly on iPhones

Currently utilizing "bootstrap": "~3.3.4" within the mean.js framework, I am facing an issue with the navbar dropdown menu. On desktop, everything functions as expected - the dropdown opens and remains open when the icon is clicked. However, once deployed ...

What is the best way to utilize an Angular service method from a controller?

As a newcomer to Angular, I have created an 'Employee Search' Service module. Let's take a look at the code: // Employee Search Service app.service('employeeSearchService', function($http, resourceServerAddress){ this.empList ...

unable to construct a Yeoman Angular application

Having some issues while building an AngularJS web app generated with Yeoman Angular generator. Running grunt serve works just fine, but when trying to build the app with grunt, encountering errors like: Running "concurrent:dist" (concurrent) task Warning ...

AngularJS Tip: Ensuring addClass is not called on directive during page load

I am facing an issue with a directive that triggers a CSS animation on page load instead of waiting for a button click event. I need the animation to only start when a button is clicked. How can I stop the animation from running automatically? JSBIN Dire ...

When using Angular $HTTP, CORS is supported when working with application/x-www-form-urlencoded, but there is a problem with OPTIONS 404

I have successfully implemented a Node + ExpressJS with CORS setup using this middleware. However, I am facing issues when working with POST requests. Here is what works: $http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded"; ...

Sending data from an Angular application using AJAX to FormSpree.io

Currently, I am using a jQuery script to send ajax requests to for static form submission. The documentation provided by FormSpree suggests the following approach: $.ajax({ url: "//formspree.io/<a href="/cdn-cgi/l/email-protection" class="__cf_email ...

Ionic app encountering issues with Facebook OAuth login functionality

Currently, I am implementing Facebook Auth for my Ionic app by using the Firebase module. Despite setting up the firebase module correctly initially, I keep encountering an error during the login process. It should be noted that the login function worked p ...

Tips for concealing links in ui-grid post-click with AngularJS

When using Angular-UI-Grid, I am working with the following paginated data: Name | Link A | Show Hide B | Show Hide Within my options: cellTemplate:'<div>' + ' <a ng-click="grid.appScope.show(row)">Show</a> ...

What could be causing the remaining part of the template to not render when using an Angular directive?

After adding my custom directive to a template on an existing page, I noticed that only the directive was rendering and the rest of the template was not showing up as expected. Even though the controller seemed to have executed based on console logs and B ...

The jQuery ajax post with dataType set to 'JSON' functions properly on Android devices but encounters errors on iPhone 4

I've encountered a strange issue while developing a phonegap application that connects to my web service. The code works perfectly on Android, but for some reason, it fails on iPhone. It's using jQuery and here is the specific part of the code ca ...

Exploring the potential of Angular JS and gapi in building a seamless routed

I'm facing a similar challenge as described in this question. However, the key difference is that I require two controllers for two distinct routes, essentially representing two different tables: ../table1 and ../table2. Each table needs to fetch data ...

Exploring the object structure received from AngularFire

Here is the Firebase query that I am running: var ref = new Firebase('https://<myfirebase>.firebaseio.com/companies/endo/status'); data = $firebaseObject(ref); console.dir(data); The object that I receive looks like this: d ...

The Ionic SQLite Porter plugin is not installed

After following the ionic prepopulated database tutorial from the link shared below, I encountered a plugin_not_installed error. Check out the Ionic prepopulated database tutorial. Despite trying the recommended solution of uninstalling and reinstalling th ...

Discover the final index of an array with Angular's ng-repeat functionality

I'm currently working with an Object that contains array values which I am trying to iterate over. Here's a simplified example of what I have: $scope.messages = { "1": [ { "content": "Hello" }, { "content": "How are you" }, { "conte ...

Updating the status of the checkbox on a specific row using Typescript in AngularJS

My goal is to toggle the checkbox between checked and unchecked when clicking on any part of the row. Additionally, I want to change the color of the selected rows. Below is my current implementation: player.component.html: <!-- Displaying players in ...

Customize the icon used for expanding and collapsing in AngularJS

I want to modify the icon (e.g., plus, minus) when clicking on an expand-collapse accordion. Currently, I am using the Font Awesome class for icons. While I know it can be easily achieved with jQuery, I'm wondering if there is a way to do this in Angu ...

What is the process for updating the curly braces in AngularJS from {{ }} to [{ }] format?

I remember there is a method to transform the ng-binding items {{ expression }} into {[ expression ]}, as I have utilized it previously. However, I am unable to recall the specific term for these items, which makes it challenging to search for further info ...

Need help with functions in JavaScript?

I'm struggling with understanding some code related to javascript and angularjs. I came across this line - !function(a,b,c){}(x,y,z) - and I can't make sense of it. It's something new to me and I would appreciate any help in clarifying its p ...