jasonaburton
jasonaburton

Reputation: 3103

navigator.geolocation.watchPosition just not working

Okay, my code is below so I'll explain what I'm doing and what I'm getting for results.

I'm trying to grab the users location using navigator.geolocation.watchPosition. I've specified both a success and error callback. The first time I get the location it's usually very inaccurate so I use watchPosition to keep getting the location until it's either tried 4 times or got a location that is accurate to within 500 metres.

Problems I am having:

I've searched many a forum post and many a stackoverflow question as well as the spec for geolocation and any other docs out there. There's not very much information on it, let alone these problems. Is there any I'm doing wrong? Or is this just the nature of working with location?

if(navigator.geolocation){
        var geo_count = 0;

        var wpid = navigator.geolocation.watchPosition(success, error, {
            enableHighAccuracy: true, 
            maximumAge: 0, 
            timeout: 10000
        });

        function success(position){
            alert(position.coords.accuracy)

            geo_count = geo_count + 1;

            if(position.coords.latitude && position.coords.longitude && position.coords.accuracy < 500){
                navigator.geolocation.clearWatch(wpid); 

                alert('position obtained!');    
            }
            else if(geo_count > 4){
                navigator.geolocation.clearWatch(wpid);

                alert('inaccurate position obtained');
            }
        }

        function error(error){
            switch(error.code){
                case 1:
                    alert('permission denied');
                    break;
                case 2:
                    alert('position unavailable');
                    break;
                case 3:
                    alert('timeout');
                    break;
                default:
                    alert('unknown error');
                    break;
            }
        }
    }

Upvotes: 11

Views: 8732

Answers (1)

Henry Ruhs
Henry Ruhs

Reputation: 1630

I recommend to check using:

if (typeof navigator.geolocation === 'object' && typeof navigator.geolocation.watchPosition === 'function') {
    ...
}

"The Geolocation.watchPosition() method is used to register a handler function that will be called automatically each time the position of the device changes. You can also, optionally, specify an error handling callback function."

Maby it doesn't trigger because the position is still the same? ^^

Try to debug it using Geolocation.getCurrentPosition() with an Interval or Webworker: https://developer.mozilla.org/en-US/docs/Web/API/Geolocation

Good luck

Upvotes: 2

Related Questions