6

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?

1 Answer 1

5

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/

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks.. What do I do if i need to utilize the values of mysrclat and mysrclong beyond the callback borders? like in my case, i need to use those values in another function..I've tried assigning it to $scope variable and using it in the other function does not work as well..any ideas?
You should bind them to scope or to implement it as a service, it's much better. You can use github.com/arunisrael/angularjs-geolocation, I guess it's very suitable for your task or review code of the service. It's very simple and use it for your porpoises.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.