Nishan Madhuwantha
Nishan Madhuwantha

Reputation: 33

Angularjs: get current location coordinate

function (position) {

    mysrclat = position.coords.latitude; 
    mysrclong = position.coords.longitude;

    console.log(mysrclat);
    console.log(mysrclong);

});

how to pass this mysrclat and mysrclong value to html page or service file?

my controller:

var lat = 0;
var lan = 0;
var mysrclat = 0;
var mysrclong = 0;
$scope.nearme = function($scope) {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      mysrclat = position.coords.latitude;
      mysrclong = position.coords.longitude;
      console.log(mysrclat);
      console.log(mysrclong);
      $scope.lat = mysrclat;
      $scope.lan = mysrclong;
    });
  }
}

Upvotes: 1

Views: 4606

Answers (3)

32teeths
32teeths

Reputation: 1509

Wrap it all in a $timeout(function(){//logic here}) . It will work as expected as $timeout internally calls the $apply & Everythin'll be fine .

Upvotes: 0

divya reddy
divya reddy

Reputation: 139

To achieve your expected results, you can $scope.$apply() or $scope.evalAsync

$scope.$apply : $apply() is responsible for executing entire list of watchers of available scopes.

From Angular documentation:
$apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). Because we are calling into the angular framework we need to perform proper scope life cycle of exception handling, executing watches.

Use below code snippet to get expected result

$scope.$apply(function() {
                $scope.lat = mysrclat;
                $scope.lan = mysrclong;
            })

$scope.evalAsync:
In some scenarios , you might get below error on using $scope.$apply heavily

Error: $digest already in progress

To avoid that , use $scope.evalAsync which will evaluate expression in current or next digest cycle

$scope.$evalAsync(function() {
                $scope.elat = mysrclat;
                $scope.elan = mysrclong;
            })

codepen url for reference- https://codepen.io/divyar34/pen/dvJrba

Upvotes: 0

Gangadhar Jannu
Gangadhar Jannu

Reputation: 4454

When you change a $scope value outside of angularJS you should manually trigger the digest cycle. One way to do that is using $scope.$evalAsync

Change your nearme function definition as below:

$scope.nearme = function($scope) {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position) {
            $scope.$evalAsync(function() {
                $scope.lat = position.coords.latitude;
                $scope.lan = position.coords.longitude;
            })
        });
    }
}

Upvotes: 2

Related Questions