このスニペットは、html5 geolocation api を使用して作成しました。ユーザーが緯度経度を許可して表示する場合{{lat}}
緯度が 2 回目のクリックでのみ表示される理由がわかりません。showPosition() はすでにトリガーされていると思いますか? 最初のクリックでコンソールに表示されます。
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);
}
});