0

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);
  }
});
5
  • 1
    Please post the code here instead of linking to an outside site. We need both the HTML and the JS. Commented Apr 11, 2013 at 18:21
  • 2
    Call $scope.$apply() at the bottom of showPosition(). The callback is called "outside" of Angular, so you need to tell Angular to run a digest cycle. Commented Apr 11, 2013 at 18:22
  • Thank @MarkRajcok , I will check out the $apply. Commented Apr 11, 2013 at 18:27
  • @MarkRajcok actually gave an answer: showPosition is called async, so code inside of that function should be wrapped by $scope.$apply(function() { ....}) Commented Apr 11, 2013 at 18:38
  • @ValentynShybanov, yeah, I didn't want to give out my coordinates :), so I wanted vzhen to test it before I wrote an actual answer. (I'm always leery about posting an answer if I can't test a modified plunker/fiddle to see if it actually works.) Commented Apr 11, 2013 at 19:02

1 Answer 1

2

Callback function showPosition is called "outside" Angular, so although your $scope properties will be updated, the view will not update because Angular doesn't know about these changes.

Call $scope.$apply() at the bottom of function showPosition(). This will cause a digest cycle to run, and Angular will notice the changes you made to the $scope (because of the $watches that Angular set up due to using {{}}s in your HTML) and update the view.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.