Roxx
Roxx

Reputation: 3996

Call/use Cordova Geolocation in Angular

I am trying to use Cordova Geolocation plugin. I have added the plugin like below.

cordova plugin add cordova-plugin-geolocation

I used the sample code from Cordova site.

 <script type ="text/javascript">
document.getElementById("watchPosition").addEventListener("click", watchPosition);  

function watchPosition() {
  var latitude,longitude;
   var options = {
      maximumAge: 3600000,
      timeout: 3000,
      enableHighAccuracy: true,
   }
   var watchID = navigator.geolocation.watchPosition(onSuccess, onError, options);

   function onSuccess(position) {
     /* alert('Latitude: '          + position.coords.latitude          + '\n' +
         'Longitude: '         + position.coords.longitude         + '\n' +
         'Altitude: '          + position.coords.altitude          + '\n' +
         'Accuracy: '          + position.coords.accuracy          + '\n' +
         'Altitude Accuracy: ' + position.coords.altitudeAccuracy  + '\n' +
         'Heading: '           + position.coords.heading           + '\n' +
         'Speed: '             + position.coords.speed             + '\n' +
         'Timestamp: '         + position.timestamp                + '\n');*/
         longitude = position.coords.longitude;
         latitude = position.coords.latitude;

   };

   function onError(error) {
      alert('code: '    + error.code    + '\n' +'message: ' + error.message + '\n');
   }
}
    </script>

If I test this on button click it is working fine means I am getting the location. So, I comment that out in this question.

Below is my Angular code.

 // define angular module/app
    var formApp = angular.module('formApp', []);

    formApp.controller('formProfile1', function($scope,$http){
    $scope.uid = 1;
    $scope.names = names;
     $scope.searchok = search;    $scope.pics = pics;
     watchPosition();
    $scope.longitude = longitude;
    alert($scope.longitude);
----- Some other codes are here ------
}

The problem is it is giving me Angular error as I am not using or calling them properly. How can it be done?

I suspect I am doing something wrong.

Upvotes: 0

Views: 800

Answers (1)

karser
karser

Reputation: 1693

You are given with location in a callback, so your code should be asynchronous.

formApp.controller('formProfile1', function($scope){
    navigator.geolocation.getCurrentPosition(function(position) {
        $scope.longitude = position.coords.longitude;
        alert($scope.longitude);
    }, function onError(error) {
        alert('code: '    + error.code    + '\n' +
              'message: ' + error.message + '\n');
    });
});

Upvotes: 1

Related Questions