Search code examples
javascriptiosmobilegeolocationmobile-safari

navigator.geolocation reporting false first value


I am currently producing a mobile web application which enables the user to walk with the application, and it will measure the distance covered (straight-line only). Obviously, using Haversine is fine and the computations work as expected. However, I have noticed a slight bug when testing on iOS 5 (iPhone 3GS, untested on 4 and 4G).

Here's the JavaScript that I am using to watch their position:

var points = [ ]; // This will be an array holding all of the points we have recorded.

// Start watching the position:
navigator.geolocation.watchPosition(function(location) {
    var this_coords = { lat: location.coords.latitude, lng : location.coords.longitude };
    points.push(this_coords);
}, function() {  }, true);

// When we're done, I output them to the console:
var start = points[0],
end = points[points.length - 1];
console.log('Start: ' + start.lat + ', ' + start.lng);
console.log('End: ' + end.lat + ', ' + end.lng);

Essentially, all of the points are recorded into an array, and then the first and last lat / long pairs are used for the Haversine. However, the initial value entered into the array always seems to be incorrect (by a significant distance). The final value is always correct (within ~ 5m).

Does anyone know why the first reading may be so inaccurate, or how I can circumvent this? I thought about perhaps just ignoring the first, and taking the second reading, but this obviously isn't very scientific.


Solution

  • The first location is the fastest to respond then it trys to narrow it down further. As it trys to connect via phone connection, wifi and gps they all come at different times.

    You could use position.coords.accuracy to narrow it down first before executing.

    e.g.

     if (position.coords.accuracy < 100){
               // if accuracy is less than 100m do something
    
        }