Geolocation cordova Android plugin does not work


#1

I am developing an application which 70% of it is based on geolocation. I began to develop in the iOS and everything works great, I had some problems but nothing that is not solvable logically. Now, I was asked a version for Android, at first impression, everything works identical to iOS, but when the testing version that give me problems arose geolocation. The problem is that being off the GPS from the phone (I tested Samsung, Xperia, Motorolas) fall into the error function (which I defined) to alert the user that the GPS was off and that should enable it to occupy. However, activating it, it does not work well, restart the computer to work correctly recently, I’m crazy, because even I get an error response, or alerts you leave, or anything like that.

My code :

$scope.$on('$ionicView.enter', function(){
$(function(){
 document.addEventListener("deviceready", onDeviceReady, false);
})

function onDeviceReady() {
 navigator.geolocation.getCurrentPosition(onSuccess, onError);
}

function onSuccess(pos) {
 $scope.latitud = pos.coords.latitude
 $scope.longitud =  pos.coords.longitude;
 console.log(pos.coords.latitude);
 $scope.mostrar_cercanos = true;
 $scope.getViews();
}

function onError(error) { 
 $scope.mostrar_cercanos = false;
 $scope.mostrar_mensaje_gps = true;
 $scope.mensaje = "El GPS de su telefono no se encuentra activado";
}
})

Plugins :

org.apache.cordova.geolocation 0.3.12 "Geolocation"
org.apache.cordova.inappbrowser 0.6.0 "InAppBrowser"
org.apache.cordova.network-information 0.2.15 "Network Information"
org.apache.cordova.splashscreen 1.0.0 "Splashscreen"

I have to go back to iOS mention that everything works as I want.


#2

Hi

I’m also using the same plugin

Install the plugin of cordova
cordova plugin add org.apache.cordova.geolocation

It is working fine in Android version Jelly Bean but is not working in Android version Kitkat.

 navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError);
       function geolocationSuccess(position) {
           var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
           var geocoder = new google.maps.Geocoder();                
           geocoder.geocode({'latLng': latlng}, function(results, status) {
               if (status == google.maps.GeocoderStatus.OK) {
                   var country = "";
                   if(results[0]) {
                       for(var i = 0; i < results[0].address_components.length; i++) {
                           if(results[0].address_components[i].types[0] == "country") {
                               country = results[0].address_components[i].long_name;
                               window.localStorage.setItem("country", country);
                               $ionicPopup.alert({
                                   title: "User Location",
                                   subTitle: "Country",
                                   template: country
                               });
                           }
                       }
                   }
               }
           });
       }

       function geolocationError(error) {
           $ionicPopup.alert({
                   title: "Pajhwok Location",
                   subTitle: "Error",
                   template: JSON.stringify(error)
           });
       }

#3

Hi, getting the same problem on Lollipop. When gps is turned off and user asked to turn on gps, once that is completed, going back and calling the function will not work. Only when app is closed and opened again will it work.

Here is my code:

controller.js:

$scope.checkLocation = function(){
    if (window.cordova) {
    cordova.plugins.diagnostic.isLocationEnabled(
                  function(e) {
                      if (e){
                        successFunctionCall();
                      }   
                      else {
                        alert("Location Not Turned ON");
                        cordova.plugins.diagnostic.switchToLocationSettings();
                      }
                  },
                  function(e) {
                      alert('Error ' + e);
                  }
              );
          }
  }
  $scope.getLocation = function(){
      $scope.checkLocation();
      $scope.supportsGeo = $window.navigator;
      $scope.position = null;
      $window.navigator.geolocation.getCurrentPosition(function(position) {
                  showToast('Getting Location...');
                  $scope.$apply(function() {
                      $scope.position = position;
                      var link = "http://maps.google.com/maps?saddr="+$scope.position.coords.latitude+","+$scope.position.coords.longitude+"&daddr="+$scope.address;

                      $window.open(encodeURI(link), '_blank', 'location=no');
                  });
                }, function(error) {
                    alert(error);
                },{enableHighAccuracy: true});
      
      }
    

    function showToast(message) {
        if (window.plugins && window.plugins.toast) {
            window.plugins.toast.showShortCenter(message);
        }
        else $ionicLoading.show({ template: message, noBackdrop: true, duration: 2000 });
    }

html:

<a ng-click="getLocation()" class="tab-item">
    <i class="icon ion-navigate"></i>Navigate
  </a>

Plugins:
Geolocation, InAppBrowser, Toast & Dianostic

Any help will be greatly appreciated!


#4

It works, you just need to know how to configure everything correctly.

  1. You will need Cordova Whitelist plugin.
  2. Correct security meta tag

Find more about it here: http://www.gajotres.net/using-cordova-geoloacation-api-with-google-maps-in-ionic-framework/


#5

Thanks for your help @Gajotres! I solved it by having a couple of loops, but if the user does not turn on their GPS, when they come back to the app, they have to click on the button again, which is a bit troublesome.
Here is my code to deal with it:

$scope.resumeLocation  = function(){
      $scope.supportsGeo = $window.navigator;
      $scope.position = null;
      // alert("Here 3");
      $window.navigator.geolocation.getCurrentPosition(function(position) {
                  showToast('Getting Location...');
                  $scope.$apply(function() {
                      $scope.position = position;
                      var link = "http://maps.google.com/maps?saddr="+$scope.position.coords.latitude+","+$scope.position.coords.longitude+"&daddr="+$scope.address;

                      $window.open(encodeURI(link), '_blank', 'location=no');
                  });
                }, function(error) {
                    alert(error);
                },{enableHighAccuracy: true});
    }


    $scope.checkLocation = function(){
    if (window.cordova) {
    cordova.plugins.diagnostic.isLocationEnabled(
                  function(e) {
                      if (e){
                        // alert("Here 2");
                        document.addEventListener("resume", $scope.resumeLocation(), false);
                        successFunctionCall();
                      }   
                      else {
                        $ionicPopup.alert({
                          title: 'Error',
                          content: 'Location Not Turned ON',
                          buttons: [{text: 'Okay',type: 'button-balanced'}]
                        }).then(function(res) {
                          console.log('Location Not Turned ON');
                          cordova.plugins.diagnostic.switchToLocationSettings();
                        });
                        // alert("Location Not Turned ON");
                        
                      }
                  },
                  function(e) {
                      alert('Error ' + e);
                  }
              );
          }
  }
  $scope.getLocation = function(){
      // alert("Here 1");
      document.addEventListener("pause", $scope.checkLocation(), false);

      }

#6

Hi @zachary545. Can u please explain how you solved the GPS turn on issue? When user turned on the GPS and again calling the getCurrentPosition function it is returning error.


#7

Hi,

There are 3 functions, getLocation, checkLocation and resumeLocation.

The only method that I actually call in my html file is getLocation. What it does is pause then call function checkLocation. What checkLocation does is to check if location has been turned on, and switches to the device settings so that the user can turn it on with ease. Once that is done, when the user goes back to the app, the function getLocation will be called again, which would trigger checkLocation again followed by resumeLocation which then produces the GPS coordinates.

Reminder, it can only work in an actual device and not the browser. Also, there are certain plugins that need to be added (Geolocation, InAppBrowser, Toast & Dianostic).

Hope it helps!


#8

man you could help me ? I’m trying to implement its same code in my application only by clicking the getLocation ( ) button does not work the same


#9

its not working in android device


#10

Was battling with this issues until i found this plugin => https://github.com/louisbl/cordova-plugin-locationservices.

The plugin exists mainly because the cordova geolocation plugin does not use Android code anymore : https://issues.apache.org/jira/browse/CB-5977. It relies on the geolocation capability of the WebView. Don’t know why no one is talking about this.

Here is a snippet of my code:

$scope.getCordinates = function() {

       if (window.cordova) {
        var PRIORITY_BALANCED_POWER_ACCURACY = 102;
        var posOptions = { maximumAge: 1000, timeout: 20000,enableHighAccuracy: false, priority: PRIORITY_BALANCED_POWER_ACCURACY };
        cordova.plugins.locationServices.geolocation.getCurrentPosition(function(position) {
            
             if(Location.init(position.coords.latitude,position.coords.longitude)){

               $scope.Data.latitude = position.coords.latitude;
               $scope.Data.longitude = position.coords.longitude;
               //Toast.show('Getting Location...', 'short', 'top');

               }else{
                $scope.Data.latitude = '';
                $scope.Data.longitude = '';
                Toast.show('Turn on Location access in settings for better sales tracking..', 'short', 'bottom');
              }
            console.log(position);

          }, function(error) {
            $scope.Data.latitude = '';
            $scope.Data.longitude = '';
            Toast.show('Error encountered with Geolocation Api', 'short', 'bottom');
            console.log(error);

          }, posOptions);
        }

     }