Getting geolocation coordinates using AngularJS

I am trying to get the latitude and longitude of my position using AngularJS and Geolocation. This is a controller function in which I assign latitude and longitude values ​​and print them 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 problem is that for the first time the coordinates are printed as 0, 0. Then, after that, the correct coordinate values ​​are printed. Why is it printing 0, 0 as coordinates for the first time?

+5
source share
1 answer

Everything is easy :) your console.log is outside the borders of the callback,

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

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

+5
source

Source: https://habr.com/ru/post/1207983/


All Articles