gpt4 book ai didi

javascript - 在 Javascript 中使用 Haversine 公式

转载 作者:行者123 更新时间:2023-12-01 11:24:49 25 4
gpt4 key购买 nike

我正在尝试使用 Haversine 距离公式(如在此处找到:http://www.movable-type.co.uk/scripts/latlong.html)但我无法让它工作,请参阅以下代码

    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' 

我理解是因为它需要执行以下操作:
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}

但是当我把它放在函数下面时,它仍然会返回相同的错误消息。如何使它使用辅助方法?或者是否有另一种方法来编写代码以使其工作?谢谢!

最佳答案

此代码有效:

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

关于javascript - 在 Javascript 中使用 Haversine 公式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14560999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com