david-d
3/30/2015 - 7:41 PM

Common JS Module for Geolocation

Common JS Module for Geolocation

// Modules
var $       = window.jQuery,
	cookie  = require('./cookie.js');

// Vars
var _geoOptions = {
	maximumAge : 12 * 60 * 60 * 1000,
	timeout    : 5000
};

var geoloc = cookie.get('geoloc');
var geoCookieIsSet = geoloc && geoloc.hasOwnProperty('lat') && geoloc.hasOwnProperty('lng') && geoloc.lat.length > 0 && geoloc.lng.length > 0;


function geoLocation() {
	$(window).trigger('Geo/Started');
	
	if (navigator.geolocation && !geoCookieIsSet) {

		navigator.geolocation.getCurrentPosition( _geoSuccess, _geoError, _geoOptions);
	} 
	else if (geoCookieIsSet) {
		$(window).trigger('Geo/GotFromGeoLocCookie');
	}
	else{ 
		cookie.set('geoloc', 'lat=&lng=');
		$(window).trigger('Geo/NotSupported');
	}
}

function _geoSuccess(position) {
	cookie.set('geoloc', 'lat=' + position.coords.latitude + '&lng=' + position.coords.longitude, 1);
	$(window).trigger('Geo/Updated');
}

function _geoError() {
	cookie.set('geoloc', 'lat=&lng=');
	$(window).trigger('Geo/Error');
}

module.exports = {
	init: geoLocation
};