I created this snippet using html5 geolocation api.
If the user allow and display the lat,lng with {{lat}}
I don't understand why the lat only display in second click. I thought the showPosition() has already triggered? You can see it show in console in the first click.
HTML:
<body ng-controller="MainCtrl">
{{lat}}
<button ng-click="getLocation()">Click</button>
</body>
JS:
app.controller('MainCtrl', function($scope) {
$scope.getLocation = function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert("Geolocation is not supported by this browser.");
}
}
function showPosition(position) {
$scope.lat = "Latitude: " + position.coords.latitude;
$scope.lng = "Longitude: " + position.coords.longitude;
console.log($scope.lat);
}
});
$scope.$apply()at the bottom ofshowPosition(). The callback is called "outside" of Angular, so you need to tell Angular to run a digest cycle.showPositionis called async, so code inside of that function should be wrapped by$scope.$apply(function() { ....})