Last active
August 29, 2015 14:09
-
-
Save argelius/2ecf0b7c08f31a11eaff to your computer and use it in GitHub Desktop.
Geolocation API as AngularJS service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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