4

I have been playing with the JavaScript Geolocation API (mostly in iOS 6 and Android Jellybean devices), and despite passing:

{
  enableHighAccuracy: true, 
  maximumAge: 0
}

as PositionOptions, the pattern seems to be that on the first response I get a fast low accuracy response (the location.coords.accuracy value has been as high as 16,130) and on the second or third response I get a high accuracy response (with a location.coords.accuracy value as low as 31). Right now I'm implementing a setTimeout call (with a 3 second delay) to query the GPS twice, and I'm ignoring the first response. But I'm wondering if anyone else has any pointers on a better implementation. Here is my code (with the 3 second timeout) (and a demo, you will need the console open)

var check = function() {
  if ("geolocation" in navigator) {
    console.log('looking');
    navigator.geolocation.getCurrentPosition(function(location) {
      console.log('Ignoring the following data:');
      console.log({
        lat: location.coords.latitude,
        lng: location.coords.longitude,
        accuracy: location.coords.accuracy});
      setTimeout(function() {
        navigator.geolocation.getCurrentPosition(function(location) {
          console.log('On my system I am firing a Lucene Spatial search with the following data:');
          console.log({
            lat: location.coords.latitude,
            lng: location.coords.longitude,
            accuracy: location.coords.accuracy});
        }, function() {
          console.log('navigator error occurred on second call... weird');
        }, {
          enableHighAccuracy: true, 
          maximumAge: 0
        });
      }, 3000);
    }, function() {
      console.log('navigator error occurred on first call.');
    }, {
      enableHighAccuracy: true, 
      maximumAge: 0
    });
  } else {
    console.log('geolocation not available');
  }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Jason Sperske
  • 29,816
  • 8
  • 73
  • 124
  • Care to show your actual code? I'm not sure how important it is, but it can't hurt – Ian Jul 02 '13 at 18:34
  • @Ian, I added the code and a JSFiddle demo – Jason Sperske Jul 02 '13 at 18:45
  • Rather than ignore the first result and keep the second, why not just assume you need to take more than one sample and schedule N checks, keeping the one with the most accuracy? – ssube Dec 28 '16 at 13:56
  • instead of `getCurrentPosition` use `watchPosition` and capture the point when is less than your critical error. https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition – Jose Hermosilla Rodrigo Dec 28 '16 at 14:00

1 Answers1

0

If your app requires so precise geolocation, then maybe you could determine what is that critical threshold for the accuracy property and set up a listener which observes the changes in accuracy and only reacts when the response is precise enough.