Skip to content

Instantly share code, notes, and snippets.

@argelius
Last active August 29, 2015 14:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save argelius/2ecf0b7c08f31a11eaff to your computer and use it in GitHub Desktop.
Save argelius/2ecf0b7c08f31a11eaff to your computer and use it in GitHub Desktop.
Geolocation API as AngularJS service
angular.module('app', [])
.factory('$geolocation', function($q) {
return {
get: function() {
var deferred = $q.defer();
navigator.geolocation.getCurrentPosition(
function(result) {
deferred.resolve(result);
},
function(error) {
deferred.reject(error);
}
);
return deferred.promise;
},
watch: function() {
var deferred = $q.defer();
navigator.geolocation.watchPosition(
function(result) {
deferred.notify(result);
},
function(error) {
deferred.reject(error);
}
);
return deferred.promise;
}
};
})
.controller('PositionController', function($scope, $geolocation) {
$geolocation.watch().then(
function() {},
function(error) {
// Something bad happened.
},
function(position) {
console.log(position);
$scope.position = position;
}
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment