Enabling, checking and disabling HTML5 geolocation

There are a lot of introduction-like posts about starting your journey with HTML5 geolocation, so I don't intend to write another one. Instead, I'm going to say a few words about enabling and disabling in-browser geolocation services, because this topic has some glitches that may not be know by everyone.

How to check, if geolocation is enabled?

The fact, that a browsers supports geolocation, doesn't mean that user allows it to be used by your page.

A piece of code as simple as:

return ((navigator.geolocation !== null) && (navigator.geolocation !== undefined));

will only tell you, if given browser supports HTML5 geolocation, but it will tell you nothing about whether user has approved or declined your website access to geolocation data. In other words, in case of decline, above code will return true, but your geolocation-aware code will fail even so (not fed with any data).

I found out, that answers to this Stack Overflow question has a great solution for this problem.

In basic, you have to use either getCurrentPosition or watchPosition, which both has two arguments and both arguments are callback functions executed when there is a success (first) or an error (second) in obtaining geolocation. Second function has a return value (error code) "PERMISSION_DENIED" designed specially to check, if geolocation has been denied.

For example you can use a code like this:

isGeolocationEnabled = function () {
    navigator.geolocation.getCurrentPosition (
        function() {
            return true;
        },
        function (error) { 
            if (error.code = error.PERMISSION_DENIED) {
                return false;
            }
            else {          
                return true;
        }
    });
}

Only this way you can detect, that member has declined your website access to geolocation data.

Notice that these functions are asynchronous.

How to really disable geolocation?

As mentioned above, following code:

return ((navigator.geolocation !== null) && (navigator.geolocation !== undefined));

only tells you, if your browser is capable of serving HTML 5 geolocation functions. Therefore, it will always be true, if your browsers does it, even if you turn off geolocation (i.e. set settings to deny geolocation data to any page).

If you want to test, how your script will work, when there is no geolocation API available at all (older browsers), you must turn off entire geolocation module.

To do this in Firefox:

  • type about:config as URL and hit Enter,
  • type geo.enabled to find this preference,
  • double click on it.

From this moment on location-aware browsing is disabled and your browser acts as it would never support HTML5 geolocation API.

In other browsers this solution should be similar (details).

Further readings

Some interesting articles that can be considered:

Leave a Reply