在Javascript中使用Haversine公式 [英] Using the Haversine Formula in Javascript
问题描述
我正在尝试使用Haversine距离公式(如下所示: http ://www.movable-type.co.uk/scripts/latlong.html )但我无法让它工作,请参阅以下代码
I'm trying to use the Haversine Distance Formula (as found here: http://www.movable-type.co.uk/scripts/latlong.html) but I can't get it to work, please see the following code
function test() {
var lat2 = 42.741;
var lon2 = -71.3161;
var lat1 = 42.806911;
var lon1 = -71.290611;
var R = 6371; // km
//has a problem with the .toRad() method below.
var dLat = (lat2-lat1).toRad();
var dLon = (lon2-lon1).toRad();
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1.toRad()) * Math.cos(lat2.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;
alert(d);
}
错误是:
Uncaught TypeError: Object -0.06591099999999983 has no method 'toRad'
我理解是因为它需要执行以下操作:
Which I understand to be because it needs to do the following:
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
但是当我把它放在函数下面时,它仍会以相同的方式返回错误信息。如何使用辅助方法?或者是否有另一种方法来对其进行编码以使其工作?谢谢!
But when I put this below the function, it still comes back with the same error message. How do I make it use the helper method? Or is there an alternative way to code this to get it to work? Thanks!
推荐答案
此代码正常运行:
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
var lat2 = 42.741;
var lon2 = -71.3161;
var lat1 = 42.806911;
var lon1 = -71.290611;
var R = 6371; // km
//has a problem with the .toRad() method below.
var x1 = lat2-lat1;
var dLat = x1.toRad();
var x2 = lon2-lon1;
var dLon = x2.toRad();
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1.toRad()) * Math.cos(lat2.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;
alert(d);
注意我是如何定义x1和x2的。
在以下网址玩游戏: https://tinker.io/3f794
Notice how I defined x1 and x2. Play with it at: https://tinker.io/3f794
这篇关于在Javascript中使用Haversine公式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!