It appears that 'getCurrentPosition' is a service call, causing your success callback function to be executed asynchronously after the promise is returned from the service.
To ensure you have the updated value of 'curPos', move your logic utilizing the 'curPos' variable into your success callback function.
.controller('MapCtrl', function($scope, $http, $rootScope) {
$scope.mappa = {};
var curPos;
if (navigator.geolocation)
navigator.geolocation.getCurrentPosition(success);
function success(pos) {
var crd = pos.coords;
curPos = crd.latitude;
console.log(curPos); // will have a defined value here
// place your logic here
};
console.log(curPos); // will be undefined as it's called before the success callback executes
})
The approach to take also depends on the specific cases you are working with.
If the 'curPos' value needs to be fetched only once:
a. At app startup - fetch the value in a home controller or parent/abstract controller and store it in a factory (shared data service). This way, any controller can access it as needed.
b. At page load - fetch the value before page load using angular UI router states and resolves. Check out for more information.
If the value requires frequent updates - in this scenario, move all logic using the variable into the success callback function (potentially multiple callbacks based on logic variations) to synchronize explicitly.