简体   繁体   中英

How to use Angular with HTML5 geolocation native API?

I'm using following code snippet to obtain the current geolocation:

angular.module('HomelandApp').controller('PlacesController', function($scope,$http, $localStorage, uiGmapGoogleMapApi) {

  uiGmapGoogleMapApi.then(function(maps) {

        navigator.geolocation.getCurrentPosition(function (pos) {
            $scope.map = { center: { latitude: pos.coords.latitude, longitude: pos.coords.longitude }, zoom: 17 };
        });
  });
});

The problem I'm facing is that I somehow have to invoke the controller twice in order to get the map rendered. This is happening when using navigator so it's not a pure Angular UI problem.

I guess they're digest cycle Angular against native JS details. How should I fix this issue?

navigator.geolocation is outside of angular core so any scope changes made within it need to notify angular to run a digest to update the view. There are several ways to do that.

Try:

 navigator.geolocation.getCurrentPosition(function (pos) {
            $scope.map = { .... };
            $scope.$apply();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM