1

I have implemented the HTML Geolocation feature on my project, however I have noticed its not always reliable.

How can I add a fallback to timeout after x seconds and display an error?

Here is my code:

function getLocation()
{
    if (navigator.geolocation)
    {
        navigator.geolocation.getCurrentPosition(showPosition);
    }
    else{x.innerHTML = "Geolocation is not supported by this browser, please manually enter your postcode above";}

    );
}

function showPosition(position)
{
    x.innerHTML = "Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude; 
}
InvalidSyntax
  • 9,131
  • 20
  • 80
  • 127
  • 1
    Possible duplicate of http://stackoverflow.com/questions/3397585/navigator-geolocation-getcurrentposition-sometimes-works-sometimes-doesnt – mccainz Apr 15 '14 at 00:38

2 Answers2

2

You can give it a callback that takes a method to handle errors:

navigator.geolocation.getCurrentPosition(
  show_map, handle_error);

function handle_error(err) {
  if (err.code == 1) {
    // user said no!
  }
}

Taken from: http://diveintohtml5.info/geolocation.html

Brian Mains
  • 50,520
  • 35
  • 148
  • 257
2

You will likely be better off adding both the error callback and the options object.

navigator.geolocation.getCurrentPosition(
  currentPositionSuccess,
  currentPositionFail,
  // maximumAge refers to the age of the location data in cache,
  // setting it to infinity guarantees you'll get a cached version.
  // Setting it to 0 forces the device to retrieve the position.
  // http://stackoverflow.com/questions/3397585/navigator-geolocation-getcurrentposition-sometimes-works-sometimes-doesnt
  { maximumAge: 15000,
    timeout: 30000,
    enableHighAccuracy: false
  }
);

The article @Brian Mains refers to is good.

I had to enable High Accuracy locating on my (Samsung) Android 4 for geolocation to work. (Maybe Power Saving locating works as well.)

Main screen > Menu button > Settings > More > Locations (turn it on) > Mode (it may look like a heading but it isn't sigh) > High Accuracy

JohnSz
  • 2,049
  • 18
  • 17
  • I've noticed you've turned off HighAccuracy in the parameters, if the device doesn't support high accuracy wont it fall back onto "normal" accuracy? – InvalidSyntax Apr 18 '14 at 09:02
  • My use case was getting an approx distance and driving time from current location to another geolocation. I did not feel high accuracy was significant. – JohnSz Apr 19 '14 at 15:47
  • 1
    High accuracy on mobile devices uses the GPS. There are reports it commonly takes 10-30 seconds to obtain. I did not feel the user would appreciate a 10-30 sec wait, plus rounding of the results would eat any additional accuracy. Basically, it depends on your use case. – JohnSz Apr 19 '14 at 15:53