angular.module('plunker', [])
.factory('GeoLocator', function ($q, $rootScope) {
var locate = function () {
var deferred = $q.defer();
// HTML5 Geolocation API
navigator.geolocation.getCurrentPosition(success, error);
// success callback
function success(position) {
$rootScope.$apply(function () {deferred.resolve(position.coords);});
}
// error callback
function error(error) {
$rootScope.$apply(function () {deferred.reject(error);});
}
// We use promise as HTML5 Geolocation API is an asynchronous process
return deferred.promise;
};
return {locate : locate};
})
.controller('MyCtrl', function ($scope, GeoLocator) {
GeoLocator.locate()
.then(function (position) {
var pos = position.longitude + ' ' + position.latitude;
$scope.position = pos;}
, function ($error) {
$scope.position = "not found";
});
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="angular.js@1.3.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.7/angular.js" data-semver="1.3.7"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="MyCtrl">
<p>{{position}}</p>
</div>
</body>
</html>
/* Put your css in here */