Skip to content

Instantly share code, notes, and snippets.

@wickdninja
Created February 27, 2015 06:01
Show Gist options
  • Save wickdninja/2d4a00d3c534c63c182b to your computer and use it in GitHub Desktop.
Save wickdninja/2d4a00d3c534c63c182b to your computer and use it in GitHub Desktop.
GeoLocation Service
(function() {
'use strict';
angular
.module('geoDemo', [])
.factory('geoService', geoService);
geoService.$inject = ['$rootScope', '$window', '$log'];
function geoService($rootScope, $window, $log) {
var service = this;
var geo = $window.navigator.geolocation;
service.error = null;
service.position = {
lat: null,
lng: null,
accuracy: null
}
activate();
return service;
function activate() {
if (geo) {
geo.getCurrentPosition(setPosition, setError);
} else {
service.error = 'Geolocation is not supported by this browser.';
}
};
function setPosition(data) {
service.position.lat = data.coords.latitude;
service.position.lng = data.coords.longitude;
service.position.accuracy = data.coords.accuracy;
$log.info('Position retrieved');
$log.info(service.position);
return service.position;
};
function setError(error) {
error.status = 'Geolocation Error';
switch (error.code) {
case error.PERMISSION_DENIED:
error.statusText = 'User denied the request for Geolocation.'
break;
case error.POSITION_UNAVAILABLE:
error.statusText = 'Location information is unavailable.'
break;
case error.TIMEOUT:
error.statusText = 'The request to get user location timed out.'
break;
case error.UNKNOWN_ERROR:
error.statusText = 'An unknown error occurred.'
break;
}
service.error = error;
$rootScope.$emit('GeoLocationError', error);
return error.data;
};
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment