Is there a way to check if geolocation has been DECLINED with Javascript?

craigmoliver picture craigmoliver · May 23, 2011 · Viewed 90.2k times · Source

I need JavaScript to display a manual entry if geolocation is declined.

What I have tried:

Modernizr.geolocation
navigator.geolocation

Neither describes if user has previously declined access to geolocation.

Answer

Cristian Sanchez picture Cristian Sanchez · May 23, 2011

watchPosition and getCurrentPosition both accept a second callback which is invoked when there is an error. The error callback provides an argument for an error object. For permission denied, error.code would be error.PERMISSION_DENIED (numeric value 1).

Read more here: https://developer.mozilla.org/en/Using_geolocation

Example:

navigator.geolocation.watchPosition(function(position) {
    console.log("i'm tracking you!");
  },
  function(error) {
    if (error.code == error.PERMISSION_DENIED)
      console.log("you denied me :-(");
  });

EDIT: As @Ian Devlin pointed out, it doesn't seem Firefox (4.0.1 at the time of this post) supports this behavior. It works as expected in Chrome and probably Safari etc.