仅接收一次WatchPosition

时间:2013-05-29 12:46:12

标签: javascript jquery cordova

我使用此代码获得第一个位置,我想继续获取它。

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 ); 
            }
        }

现在我保留old_positionnew_positionrun_total作为全局变量。我将最后一个位置保存为新位置,将之前的位置保存为旧位置,然后计算距离并将其添加到全局变量中。

但是watchPosition仅调用UserLocationCalculation一次,之后它就不再调用它了。

1 个答案:

答案 0 :(得分:2)

您的UserLocationCalculation函数只被调用一次,因为在else子句的末尾,您正在调用navigator.geolocation.clearWatch( watchID );。由于您正在调用此设备,设备将停止监视位置更改,因此它永远不会再次触发。

来自docsStop watching for changes to the device's location referenced by the watchID parameter.