user2297790
user2297790

Reputation: 95

Getting Geolocation coordinates using AngularJS

I am trying to get the latitude and longitude of my position using AngularJS and Geolocation. This is the function in the controller in which I am assigning the values of the latitude and the longitude and printing them out to the browser console. The nearme() function is called,

  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);
    }
}

The issue is that, the first time, the coordinates print as 0, 0. Then, after that it prints the correct values of the coordinates. Why is it printing 0, 0 as the coordinates the first time?

Upvotes: 6

Views: 11918

Answers (1)

Gleb Vinnikov
Gleb Vinnikov

Reputation: 468

Everything is easy :) your console.log is located beyond collback borders,

function (position) {
  mysrclat = position.coords.latitude; 
  mysrclong = position.coords.longitude;
  console.log(mysrclat);
  console.log(mysrclong);
});

http://jsfiddle.net/glebv/axrw7g90/18/

Upvotes: 5

Related Questions