theplau
theplau

Reputation: 980

How do I get Geolocation watchPosition to run until I get an accurate result?

I've been using the Geolocation navigator.geolocation.getCurrentPosition but found that it's not as accurate as navigator.geolocation.watchPosition. So my idea is to let run navigator.geolocation.watchPosition until it gets an accuracy of <=100 and then show the position, or an error if it fails within 15 seconds.

Here's what I got:

function getLocation() {
    if (navigator.geolocation) {
        var geo_options = {
            enableHighAccuracy: true,
            timeout: 15000,
            maximumAge: 0
        };
        var watchID = navigator.geolocation.watchPosition(
            showPosition,
            showError,
            geo_options
        );
    } else {
        // Error here. Geolocation disabled.
    }
}

function showPosition(position) {
    if (position.coords.accuracy > 100) {
        // Keep trying
    } else {
        // Fire up the map, we got a position!
        // Clear the watchID.
        navigator.geolocation.clearWatch(watchID);
    }
}

My problem here is that I can't clear the watchID on success for some reason because it says it's undefined. I guess that's because the function is outside.

Is there an easy way to do this so that showPosition is only fired when the accuracy is below 100? Right now showPosition is fired at any time because it's inside the watchPosition function.

Upvotes: 0

Views: 655

Answers (1)

Mike Cluck
Mike Cluck

Reputation: 32511

That's because watchID is undefined. You've defined it within the scope of getLocation which does not share its scope with showPosition. Try declaring it outside of both of them.

var watchID;

function getLocation() {
  ...
  watchID = navigator.geolocation.watchPosition(showPosition, showError, geo_options);
}

function showPosition(position) {
  if (position.coords.accuracy <= 100) {
    navigator.geolocation.clearWatch(watchID);
  }
}

Pro-tip: if your code was running in strict mode it would have alerted you to this error.

'use strict';

function declareX() {
  var x = 1;
}

function useX() {
  console.log(x);
}

declareX();
useX();

Upvotes: 2

Related Questions