Error: Access to GPS in AngularJs blocked when user is not in the

I'm currently developing a Cordova application that utilizes different AngularJS states. Strangely, when I call geolocation.watchposition in the first state, everything works perfectly fine. However, if I try to call it in the second state, I encounter an "access denied" issue.

State transitions are triggered by a button click. Interestingly, regardless of which state I start with, only the first state seems to have access to GPS while the second one doesn't.

EDIT: It's worth mentioning that this setup works without any issues in a browser, but fails on my Android device.

Any ideas on what might be causing this discrepancy?

index.js

.config(function ($stateProvider, $urlRouterProvider) {
    $stateProvider
    .state('app', {
      url: '/app',
      templateUrl: 'templates/main_menu.html',
      controller: 'AppCtrl'
    })

   .state('map', {
       url: '/map',
       templateUrl: 'templates/map.html',
       controller: 'MapCtrl'
   });

   //First State
   $urlRouterProvider.otherwise('/app');
});

controller.js

.controller('AppCtrl', function ($scope, $rootScope, $ionicHistory, $http, $window) { 
  $scope.accPos = function () {
      var id, target, options;

      function success(pos) {
          alert("Pos: " + pos.coords.latitude + " " + pos.coords.longitude);
      }

      function error(err) {
          alert('ERROR(' + err.code + '): ' + err.message);
      }

      options = {
          enableHighAccuracy: false,
          timeout: 6000,
          maximumAge: 0
      };

      id = navigator.geolocation.watchPosition(success, error, options);
   };

   $scope.accPos();
}

//The following code block looks exactly the same
.controller('MapCtrl', function ($scope, $rootScope, $ionicHistory, $http, $window) { ... }

Answer №1

It would be beneficial to move this code snippet to a service for better sharing across your controllers. Additionally, utilizing the resolve feature of ui-router can ensure the GPS location is resolved for each state that requires it.

Here's an example implementation:

service.js

.factory('LocationService', function ($window) { 
    var id, target, options, lastPosition;
    options = {
        enableHighAccuracy: false,
        timeout: 6000,
        maximumAge: 0
    };

    var locationService = {
        startWatching: startWatching,
        stopWatching: stopWatching,
        getLastPosition: getLastPosition,
        options: options
    };  
    startWatching();
    return locationService;

    function getLastPosition() {
        return lastPosition;
    }

    function startWatching() {
        id = $window.navigator.geolocation.watchPosition(success, error, options);
    }

    function stopWatching() {
        $window.navigator.geolocation.clearWatch(id);
    }

    function success(pos) {
        lastPosition = pos;
        alert("Current Position: " + pos.coords.latitude + " " + pos.coords.longitude);
    }

    function error(err) {
        alert('ERROR(' + err.code + '): ' + err.message);
    }
});

index.js

.config(function ($stateProvider, $urlRouterProvider) {
    $stateProvider
    .state('home', {
      url: '/home',
      templateUrl: 'templates/home.html',
      controller: 'HomeCtrl',
      resolve: {
         currentLocation: function(LocationService){
            return LocationService.getLastPosition();
         }
      }
    })

   .state('map', {
       url: '/map',
       templateUrl: 'templates/map.html',
       controller: 'MapCtrl',
       resolve: {
         currentLocation: function(LocationService){
            return LocationService.getLastPosition();
         }
      }
   });

   //Default State
   $urlRouterProvider.otherwise('/home');
});

controller.js

.controller('HomeCtrl', function ($scope, $rootScope, $ionicHistory, $http, $window, LocationService, currentLocation) {
    // Display the current location at the beginning
    alert("Current Position: " + currentLocation.coords.latitude + " " + currentLocation.coords.longitude);

    // Watch for changes in location from the service
    $scope.$watch(function () {
        return LocationService.getLastPosition();
    },
    function (newValue, oldValue) {
        if (newValue !== oldValue) {
            // Perform some actions
        }            
    }, true);
}

Please note that this code has not been tested thoroughly. It is solely intended to convey the concept.

Cheers!

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

Adding a PDF generated from an HTML div to an email using Java

I am looking for a solution to convert the contents of an HTML div tag into a PDF file while preserving its associated CSS. This is essential as I will be using Java on the back-end to send emails, and I need to attach the PDF with the CSS intact when send ...

The dynamic radio view creation failed to be displayed

In my attempt to position a radio group button at the start in my class, I am encountering issues with proper placement. Below is a snippet of my class view: layout.xml file <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" an ...

Updating the language of the months displayed in the popup calendar

I am attempting to change the language of the clickDate function from English (Jan, Dec, etc.) to another language. However, I am struggling to find a way to do so because I only have access to the scripts provided below. The idate is in the format 2015073 ...

How can I dynamically load a 3D model (in JSON format) at the current location of the mouse using Three.JS?

I'm currently working on a feature that involves loading a 3D model based on the mouse's position. Utilizing jQuery drag and drop functionality for this purpose has helped me load the model onto the canvas successfully, but I'm facing issues ...

Dealing with onError in RxJava can be a challenge. I recently encountered an issue where I was receiving an "OnErrorNotImplementedException

For my application, I have integrated the ReactiveLocationProvider library (link) to handle location updates. Everything works smoothly while the device is connected to the internet. However, if I disable wifi and wait for background location updates, the ...

What is the process for verifying a form when it is submitted?

Currently, I am working on validating a form onSubmit within my React Application. My goal is to enhance it with features such as adding a red outline and displaying an error placeholder inside the input when any of the conditions return false. This parti ...

The Angular user interface typeahead feature fails to automatically fill in the text box when an option is

Utilizing the Angular UI typeahead directive has been quite helpful for me. I am working with a list of individuals in the typeahead dropbox, where each person is represented as an object with details like LastName, FirstName, CustomerNumber, and more. Des ...

Pressing the border will not trigger any events

I'm facing an issue with using animation in CSS and event handlers in JS. Specifically, I have two styles for my button (normal and with the :active suffix) to simulate clicking the button. However, when I use the ng-click directive on the button in A ...

What is the best way to extract the initial n rows of a JSON String array using JavaScript?

Currently, I am working with a JSON string that represents an array. arrayString = "[ { fName: 'John', lName: 'Doe'}, { fName: 'Jane', lName: 'Doe'}, { fName: 'Josh', lName: 'Doe'}, { fNa ...

What steps do I need to take to successfully get this JavaScript Timer working?

I'm currently working on developing a timer using JavaScript. However, I've encountered an issue where the timer does not stop once it reaches zero. I've attempted to use return and if statements without success. Is my approach correct, or i ...

How about: "Using Node.js and Express to declaratively define a route for

I am facing an issue managing my routes in declarative objects and initializing/registering the endpoint handlers using one or more of these objects. The problem arises when I attempt to register the handlers in a loop of the declarative routes, methods, ...

Amchart 5: Tracking Cursor Movement on the X Axis

I am a beginner with amCharts5 and I am in need of assistance to retrieve the actual X value of the cursor on my chart (where the X axis represents dates). I have come across helpful examples for amCharts 4, but nothing seems to work for amCharts 5. Is thi ...

The method xxx is not defined within my ViewModel

Why am I encountering an error Uncaught TypeError: this.createRow is not a function when constructing the matrixLengthsAvailable array? The createRow function is defined at the end of my viewmodel... function TabBuyHarvesterModel() { self = this; ...

AngularJS: The behavior of an element is altered when compiled with a different directive

Currently, I am encountering inconsistent behavior with a directive when I $compile the element containing the said directive. Specifically, I have a directive designed to validate whether a password matches another password field. The structure of this di ...

A guide on tallying blog categories using Django and showcasing them on a template

I'm currently learning how to build a blog using Django, and I have functions for post_list, category_detail, and post detail. However, I'm facing an issue with the post_list function that renders a blog.html page. I want to display the blog cate ...

Error animation on client-side validation not resetting correctly

Incorporated a form validation and error display system utilizing TransitionGroup for animations. The flag issueVisible manages the visibility of the error message, while determineField() aids in identifying the field related to the error. The issue arise ...

Is it possible for Angular to perform bidirectional data binding in reverse between two input fields?

I'm struggling to get my two input fields to update values when the opposite input is changed. My goal is to create a simple $dollar to Gold oz calculator with two input fields. You can see a sample preview here: http://embed.plnkr.co/dw6xL95zRqJC1p ...

Reasons for aligning inline elements with input boxes

I am facing a challenge with aligning a series of inline elements, each containing an input text box, within a single row. The number and labels of these input boxes can vary as they are dynamically loaded via AJAX. The width of the div housing these inli ...

JQuery Mobile's Panel widget is the culprit behind the demise of the

I'm having some trouble adding a panel to my jQuery mobile page. Every time I try to input the code, all I see is a white screen with the loading widget, and nothing else happens. I have JQuery 2.0.0 hosted by Google, JQuery Mobile JS 1.3.1 hosted by ...

Tips for correctly implementing Headers in AngularJS version 1.6

Currently, I am attempting to incorporate headers in a GET request using the $http method. This is the snippet of code that I have implemented: this.http.defaults.headers.common['Authorization'] = 'Bearer mytoken123123'; this.http.def ...