计算两个纬度 - 经度点之间的距离?

时间:2015-10-15 09:55:12

标签: gps

我需要计算两个GPS点之间的距离。我在之前的帖子中找到了这个功能:

function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
  var R = 6371; // Radius of the earth in km
  var dLat = deg2rad(lat2-lat1);  // deg2rad below
  var dLon = deg2rad(lon2-lon1);

  var a = 
    Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(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; // Distance in km

  return d;
}

我尝试过,但没有意义。我们说我没有动,因此lat1lat2是相同的。因此,dLatdLon都是0.因此,术语a将为0.术语c = 2 * Math.atan2(0,1) = 3.141593(我使用Excel获取此数字)和距离{ {1}}。

我正在计算在给定两个GPS点的情况下每秒移动一次的车辆的距离。我期待的数量很少。这有什么不对?

2 个答案:

答案 0 :(得分:0)

您使用的公式称为Haversine公式 它工作得非常好,特别适合短距离工作。 我检查了你的代码到我的实现,我看到你的工具有一个错误

您正在使用的半身定制公式应使用以米为单位的地球半径,为什么要使用千克来表示R?

你的问题:

  

“期限c = 2 * Math.atan2(0,1)= 3.141593(我使用Excel获取此数字)”

这是你的假设中的错误。术语c = 0.很高兴,你提到了Excell。 Excell对atan2()的参数使用反转顺序,但是你必须写atan2(1,0)。

此外: 如果将R校正到单位表无法确定 所有变量都是双重类型 当我看到你的代码时,我担心某个地方会以一种方式静默地转换为一个int。

如果这一切都没有帮助:
请显示lat1,lon1,lat2,lon2的示例输入以及a和c的中间值。并确保你的deg2rad()工作。 (将R校正为米后)

答案 1 :(得分:-1)

我使用了这段代码 - 它工作正常。

    public static double distance(MyLocation p1, MyLocation p2) {
    double theta = p1.mLongitude - p2.mLongitude;
    String unit = "K";
    double dist = Math.sin(deg2rad(p1.mLatitude)) * Math.sin(deg2rad(p2.mLatitude))
            + Math.cos(deg2rad(p1.mLatitude)) * Math.cos(deg2rad(p2.mLatitude)) * Math.cos(deg2rad(theta));
    dist = Math.acos(dist);
    dist = rad2deg(dist);
    dist = dist * 60 * 1.1515;
    if (unit == "K") {
        dist = dist * 1.609344;



    } else if (unit == "N") {
        dist = dist * 0.8684;
    }

    return (dist);
}

它以千米计算距离。