toRad()Javascript函数抛出错误

pta*_*mzz 60 javascript geolocation

我正在尝试使用此处描述的技术计算两个点之间的距离(我有纬度和经度),计算两个纬度 - 经度点之间的距离?(Haversine配方)

代码如下Javascript:

var R = 6371; // Radius of the earth in km
var dLat = (lat2-lat1).toRad();  // Javascript functions in radians
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; // Distance in km
Run Code Online (Sandbox Code Playgroud)

但是当我尝试实现它时,错误就出现了Uncaught TypeError: Object 20 has no Method 'toRad'.

我需要一个特殊的库或什么来获得.toRad()工作吗?因为它似乎搞砸了第二行.

Cas*_*jne 111

你缺少一个函数声明.

这种情况下, toRad()必须首先定义为:

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

根据页面底部的代码段


Chr*_*ray 25

或者在我的情况下,这不起作用.这可能是因为我需要在jquery中调用toRad().我不是100%肯定,所以我这样做:

function CalcDistanceBetween(lat1, lon1, lat2, lon2) {
    //Radius of the earth in:  1.609344 miles,  6371 km  | var R = (6371 / 1.609344);
    var R = 3958.7558657440545; // Radius of earth in Miles 
    var dLat = toRad(lat2-lat1);
    var dLon = toRad(lon2-lon1); 
    var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * 
            Math.sin(dLon/2) * Math.sin(dLon/2); 
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
    var d = R * c;
    return d;
}

function toRad(Value) {
    /** Converts numeric degrees to radians */
    return Value * Math.PI / 180;
}
Run Code Online (Sandbox Code Playgroud)


Sal*_*ali 23

我需要为我的项目计算点之间的很多距离,所以我继续尝试优化代码,我在这里找到了.平均而言,在不同的浏览器中,我的新实现运行速度几乎是此处提到的3倍.

function distance(lat1, lon1, lat2, lon2) {
  var R = 6371; // Radius of the earth in km
  var dLat = (lat2 - lat1) * Math.PI / 180;  // deg2rad below
  var dLon = (lon2 - lon1) * Math.PI / 180;
  var a = 
     0.5 - Math.cos(dLat)/2 + 
     Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * 
     (1 - Math.cos(dLon))/2;

  return R * 2 * Math.asin(Math.sqrt(a));
}
Run Code Online (Sandbox Code Playgroud)

您可以使用我的jsPerf(由于Bart得到了很大的改进)并在此处查看结果.