Henk Jansen
Henk Jansen

Reputation: 1142

Receiving WatchPosition only once

I use this code to get the first position ,and i want to keep getting it.

var init = function()
{
       navigator.geolocation.getCurrentPosition(function(position)
       {
          new_position = position;
        }, onError, {});

      watchID = navigator.geolocation.watchPosition(UserLocationCalculation, onError,   {maximumAge: 1000,   timeout: 5000, enableHighAccuracy: true});
}

var UserLocationCalculation = function(position)
        {
            var d;
            //alert("Position" + " Latitude "  + position.coords.latitude + " Longitude " + position.coords.longitude);
            if(new_position == 0)
            {
                new_position = position;
            }
            else
            {
                //Change the positions around
                old_position = new_position;
                new_position = position;
                var conv_old_position = new google.maps.LatLng(old_position.coords.latitude, old_position.coords.longitude);
                var conv_new_position = new google.maps.LatLng(new_position.coords.latitude, new_position.coords.longitude);
                d = google.maps.geometry.spherical.computeDistanceBetween(conv_old_position, conv_new_position);
                run_total = parseInt(run_total);
                d = parseInt(d);    
                run_total += d;
                navigator.geolocation.clearWatch( watchID ); 
            }
        }

Now i keep an old_position, a new_position and a run_total as global variables. I save the last position as the new, and the one before that as old, and then calculate the distance and add this to a global variable.

But the watchPosition calls the UserLocationCalculation only once, after that, it just doesn't call it anymore.

Upvotes: 1

Views: 1207

Answers (1)

MBillau
MBillau

Reputation: 5376

Your UserLocationCalculation function is only being called once because at the end of the else clause, you are calling navigator.geolocation.clearWatch( watchID );. Since you are calling this, the device stops watching for position changes, so it never fires again.

From the docs: Stop watching for changes to the device's location referenced by the watchID parameter.

Upvotes: 2

Related Questions