我有每秒30秒向服务器发送当前坐标的jquery代码。 它适用于具有良好数据覆盖信号的区域。但是,当信号不稳定时(数据覆盖可用且反复消失),它会崩溃。几次,应用程序只是在try ... catch部分没有任何警告的情况下崩溃。
我需要检查数据覆盖是否可用,然后不断向服务器发送坐标,否则只需继续检查,直到数据覆盖可用。
这是我的代码:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" charset="utf-8" src="cordova-2.0.0.js">
</script>
<script src="jquery-1.5.2.min.js"></script>
<script src="main.js"></script>
<script src="jquery.mobile-1.0a4.min.js"></script>
<script>
var netCoverage = false;
var lat='';
var lon='';
document.addEventListener("deviceready", onDeviceReady, false);
document.addEventListener("pause", onDeviceReady, false);
function checkConnection() {
var networkState = navigator.network.connection.type;
var states = {};
states[Connection.UNKNOWN] = 0; //'Unknown connection';
states[Connection.ETHERNET] = 1; //'Ethernet connection';
states[Connection.WIFI] = 2; //'WiFi connection';
states[Connection.CELL_2G] = 3; //'Cell 2G connection';
states[Connection.CELL_3G] = 4; //'Cell 3G connection';
states[Connection.CELL_4G] = 5; //'Cell 4G connection';
states[Connection.NONE] = 6; //'No network connection';
//alert('Connection type: ' + states[networkState]);
if(states[networkState]!=0 && states[networkState]!=6)
netCoverage = true;
else
netCoverage = false;
}//ends checking for network connection
var watchID = null;
function onDeviceReady() {
checkConnection();
// Get the most accurate position updates available on the
// device.
var options = { maximumAge:30000, enableHighAccuracy: true };
watchID = navigator.geolocation.watchPosition(onSuccess,
onError, options);
// Update compass every 3 seconds
var watchID = null;
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: '+ error.code+'\n'+'message:'+
error.message + '\n');
}
$(document).ready(function() {
/*****************************/
(function worker() {
try{
if(netCoverage){
$.ajax({url: 'http://www.myurl.com/add_position.php?&lat='
+lat+'&lon='+lon,
success: function(data) {
$("#geo_info").text(data);
accIndex=0;//reset after submitting to server
},
error: function(request, error){
$("#geo_info").text("Network error: "+error);
$.ajax(this);
return;
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(worker, 30000);
}
});
}//ends checking for connection
else{
$("#geo_info").text('Unknown or no network connection.');
setTimeout(worker, 30000); //After calling this
//method few times in weak data coverage,
// the app crashes with no warning
}
}catch(err){
$("#geo_info").text('ALMOST CRASHED, '+err.message);
$.ajax(this);
return;
}
})();
/*************************************************/
});
</script>
</head>
<body>
<p id="geo_info">Watching geolocation...</p>
<button onclick="clearWatch();">Clear Watch</button>
</body>
</html>