简体   繁体   中英

HTML5 Geolocation timeout

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; 
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM