Hi i have installed ngCordova and trying to accesss the lat long value using this function
$scope.lat = '';
$scope.long = '';
var posOptions = {timeout: 10000, enableHighAccuracy: false};
$cordovaGeolocation.getCurrentPosition(posOptions)
.then(function (position) {
$scope.lat = position.coords.latitude
$scope.long = position.coords.longitude
}, function (err) {
// error
});
console.log($scope.lat, $scope.long);
When i console it exactly below the assignment of values to lat and long variables then it provide me the result on console but when i console it outside as i have displayed in the question, it shows me empty string. What is it happening?
edit: The reason why you see a correct
console.log
output when you put it inside the.then
function is that this code is actually executed asynchronously. You can learn more about it from this question on StackOverflow.I'll try to explain in my words: when you call the
.getCurrentPosition
function you just "leave it be", continue executing all other code, and "wait for it to finish" - and you wait for it inside the.then
function. So, if you putconsole.log
outside the.then
function, it will actually execute before you get the actual coordinates - thus, it will print empty values, since they just may not yet exist.Try it like this: