Getting Geolocation coordinates using AngularJS

11,778

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/

Share:
11,778
user2297790
Author by

user2297790

Updated on June 08, 2022

Comments

  • user2297790
    user2297790 almost 2 years

    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?

  • user2297790
    user2297790 over 9 years
    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?
  • Gleb Vinnikov
    Gleb Vinnikov over 9 years
    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.