1

I am trying to use HTML5 gelolocation to get the current visitor's location. Due to privacy, the browser will prompt the user to allow/disallow sharing their location with the site.

If the user does NOT allow sharing their location, I want to display a message to the console.

Here is what I have done

$(function() {

    // Try HTML5 geolocation.
    if (navigator.geolocation) 
    {
        navigator.geolocation.getCurrentPosition(function(position)
        {
            findClosestStore(position.coords.latitude, position.coords.longitude);
        }, displayMapWithAddressBar);

    } 
    else 
    {
        // Browser doesn't support Geolocation
        console.log('browser does not support geolocation!')
        displayMapWithAddressBar();
    }

});


function displayMapWithAddressBar()
{
    console.log('Show the map since the location was not detected!');
}

But when the user refuse to share their location, I don't see anything in the console. I expect to see a message to say Show the map since the location was not detected!

How can I know that a user refused to share their location?

UPDATE

My code work as expected in google Chrome but not in Firefox. How can I get this to work in all browsers?

Jaylen
  • 39,043
  • 40
  • 128
  • 221
  • 2
    Already answered here: http://stackoverflow.com/questions/6092400/is-there-a-way-to-check-if-geolocation-has-been-declined-with-javascript – Korgrue Oct 25 '16 at 17:08
  • @Korgrue I don't see an answer on the list you provided. My code in the question works just fine in Google Chrome but not Firefox. – Jaylen Oct 25 '16 at 17:20
  • In Firefox, you have to implicitly grab the lat and log individually. function showPosition(position) { alert(position.coords.latitude + “ “ + position.coords.longitude); } navigator.geolocation.getCurrentPosition(showPosition); I would test for null on either lat or long for FF geolocation enabling. – Korgrue Oct 25 '16 at 21:45

1 Answers1

0

There is no way to distinguish whether or not they denied the permission or if their browser is simply not compatible (In Firefox, at least). The way to do it is to display the map with the address bar, or whatever the default behavior is, and then update the UI if and when they accept. This code is much simpler...

displayMapWithAddressBar();
navigator.geolocation.getCurrentPosition(function(position){
    findClosestStore(position.coords.latitude, position.coords.longitude);
});
I wrestled a bear once.
  • 22,983
  • 19
  • 69
  • 116