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> 

但只是没有任何反应。谢谢

4

1 回答 1

2

toRad is not a native javascript function. You must declare it before using it.

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

Code from here : toRad() Javascript function throwing error

You can check this jsfiddle : http://jsfiddle.net/ySsQ3/

By the way, you really should put your javascript code at the end of the body (and not in the head)

于 2012-11-24T12:50:46.073 回答