2012-11-24 81 views
1

我知道這是一個重複的問題,但我不得不問,因爲我的代碼不工作。我不知道爲什麼不。如何使用相應的緯度和經度值計算兩個地點之間的距離?

我的代碼:

<!DOCTYPE html> 
<html> 
<head> 
<script> 
function displayDistance() 
{ 

var R = 6371; // km 
var dLat = (23.87284-23.76119).toRad(); 
var dLon = (90.39603-90.43491).toRad(); 
var a = Math.sin(dLat/2) * Math.sin(dLat/2) + 
     Math.cos(23.76119.toRad()) * Math.cos(23.87284.toRad()) * 
     Math.sin(dLon/2) * Math.sin(dLon/2); 
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
var d = R * c; 
document.getElementById("demo").innerHTML=d; 
} 
</script> 
</head> 
<body> 
<div id="demo"></div> 
<button type="button" onclick="displayDistance()">Display Distance</button> 

</body> 
</html> 

但就什麼都不會發生。 謝謝

回答

2

toRad不是原生的javascript函數。你必須在使用它之前聲明它。從這裏

/** Converts numeric degrees to radians */ 
if (typeof(Number.prototype.toRad) === "undefined") { 
    Number.prototype.toRad = function() { 
    return this * Math.PI/180; 
    } 
} 

代碼:toRad() Javascript function throwing error

您可以檢查此的jsfiddle:http://jsfiddle.net/ySsQ3/

順便說一句,你真的應該把你的JavaScript代碼在body結束時(而不是在head

相關問題