我得到了计算距离的脚本,我用2点(pos1,pos2)我的坐标(两者都是地理位置)然后我放了一个循环,每隔5/10秒为脚本充电,我用一个保存距离LocalStorage出一个循环。 现在我想离开循环,有一个变量来计算总距离,或者更确切地说是计算循环传递的所有距离。 这是代码:
(function(){
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
pos1 = position.coords.latitude;
pos11= position.coords.longitude;
console.log('latitudine ' + pos1);
console.log('longitudine ' + pos11);
//Passano 2 secondi
setTimeout(function(){
pos2 = 45.2968571;
pos22 = 12.034978499999966;
console.log('latitudine ' + pos2);
console.log('longitudine ' + pos22);
alert("Sono passati 2 secondi");
},2000);
// Converte in radianti
setTimeout(function(){
if (typeof(Number.prototype.toRad) === "undefined") {
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
}
// From Caspar Kleijne's answer ends
// From cletus' answer starts
var R = 6371; // km
var dLat = (pos2-pos1).toRad();
var dLon = (pos22-pos11).toRad();
var lat1 = pos1.toRad();
var lat2 = pos2.toRad();
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var distance1 = R * c;
var distance2 = distance1;
console.log(distance1, distance2);
alert('hai percorso: ' + distance1 + 'm ');
var distance2 = localStorage.setItem('key', distance2);
},2000);
})
}
setTimeout(arguments.callee, 10000);
})();
(function(){
setTimeout(function(){
var distanza = localStorage.getItem('key', 'distance2');
var distanza1 = distanza;
// here i wont calculate the total distance
console.log('prima: ' + distanza + 'n\totale: ' + total);
},6000);
setTimeout(arguments.callee,10000);
})();