Question

I'm having trouble with the most basic aspect of geolocation - no matter what I do, I don't seem to be able to get the fallback to trigger. Here's the code:

if (navigator.geolocation) {

navigator.geolocation.getCurrentPosition(function(position){

var latitude = position.coords.latitude;  
var longitude = position.coords.longitude;
var latNum = parseFloat(latitude);
var longNum = parseFloat(longitude);

This is immediately followed by a nested bunch of if...else if statements that trigger different functions based on the user's location within one of a number of defined areas and an else statement to catch the condition where the user is not in any of the defined locations. This part all works fine, including the 'else' condition at the end. Where it falls over is if the user's device does not have geolocation enabled, or the user denies access to location data when prompted.

The code supposed to capture this is simply:

} else {
   function10();
}

I have tried this in FF, Safari and Chrome with the same results: if I disable location services or deny access when prompted, the final 'else' function does not trigger.

I've looked at countless examples of this sort of elegant failure on geolocation and can't see why it doesn't work.

I'd be truly grateful for any clues where I went wrong.

Was it helpful?

Solution

OK - problem solved! I'm not sure if I feel just silly or enlightened, but for the benefit of anyone else with the same problem, here's the solution:

if (navigator.geolocation) {

navigator.geolocation.getCurrentPosition(function(position){

 // Do something here if you get position data

    },

function() {

// Do something else if you don't get any position data 
           }
       ); 
     } 

Where i went wrong, I think, is that I needed to look for a failure of the function(position)rather than the absence of a geolocation enabled agent. The second function within the same if condition provides the action in the event of no position data being returned from the browser, no matter what the reason. The final 'else' statement in the original code (above) would only be triggered on a device with no geolocation capacity.

This all makes sense now, but I have to say the documentation on Google, and many of the tutorial sites was far from clear on this, with frequent references to my initial syntax covering the situation where geolocation capacity was not enabled (as distinct from not present).

Thanks to this answer on SO for pointing me in the right direction.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top