17

Apart from setting a cookie the first time round, is there a way of detecting whether a user has already given permission for navigator.geolocation to return the lat/long of the browser?

If there is, what is it and is it the same across all browsers or different across all browsers?

This subject has been partially answered elsewhere

According to GeoLocation API – Chrome / Safari – Permission management and Visual Differences, Chrome asks for a revokable one-time permission. I haven't finished reading the article, but it would seem that storage of permissions is not a purely-Chrome thing to do.

Community
  • 1
  • 1
bugmagnet
  • 7,233
  • 7
  • 57
  • 121

3 Answers3

25

What about using localStorage which should be supported by all html5 browsers (that support geoLocation)

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
} 
//Get latitude and longitude;
function successFunction(position) {
    var lat = position.coords.latitude;
    var long = position.coords.longitude;

    localStorage['authorizedGeoLocation'] = 1;
}

function errorFunction(){
    localStorage['authorizedGeoLocation'] = 0;
}

function checkauthorizedGeoLocation(){ // you can use this function to know if geoLocation was previously allowed
    if(typeof localStorage['authorizedGeoLocation'] == "undefined" || localStorage['authorizedGeoLocation'] == "0" ) 
        return false;
    else 
        return true;
}

And then you check using the below function :

alert(checkauthorizedGeoLocation());

This is the jsfiddle if you need to check

Mehdi Karamosly
  • 4,996
  • 1
  • 25
  • 46
4

According to the spec, no - there's just the three methods on navigator.geolocation. However saving to a cookie or local storage is probably perfectly suitable - the permission is also stored in the user agent, so it should work correctly as the user moves between browsers.

AshleysBrain
  • 20,705
  • 15
  • 81
  • 119
  • However, the "Prompting for permission" section in https://developer.mozilla.org/en-US/docs/WebAPI/Using_geolocation?redirectlocale=en-US&redirectslug=Using_geolocation would appear to imply that at least one browser has a mechanism to store permission. – bugmagnet May 20 '13 at 03:11
  • That appears to only apply to Firefox addons, not general web content. – AshleysBrain May 20 '13 at 11:25
1

Please see this answer on how to do it using the Permissions API: Check if Geolocation was allowed and get Lat Lon

Works without prompting the user if permission was granted previously.

codeMonkey
  • 2,788
  • 2
  • 25
  • 41
  • 1
    Note however that Permission API is not supported by all major browsers, namely Safari and iOS Safari: https://caniuse.com/#feat=permissions-api – jfloff Jun 25 '19 at 08:48