Set a cookie, check if the cookie exists and just return if it does exists. Then you can set a cookie to expire for however long you want and it won't ask again until that cookie is expired.
function getGeoLocation() {
if (getCookie('cookie-name-here')) return;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(setGeoLocation, showGeoError, {
maximumAge: 6E4, // 6 followed by 4 zerors => 60000 milliseconds
timeout: 5E4 // 5 followed by 4 zeros => 50000 milliseconds
});
} else {
console.log('Geolocation is not supported by this browser.');
}
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return '';
}
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = 'expires=' + d.toUTCString();
var maxAge = 'max-age=' + exdays * 24 * 60 * 60;
var path = 'path=/';
document.cookie = cname + "=" + cvalue + "; " + expires + "; " + maxAge + '; ' + path;
}
The setGeoLocation
and showGeoError
would be application specific so I've left that out.