Nan使用纬度和经度计算距离

时间:2013-04-23 12:58:26

标签: android gps latitude-longitude

我正在计算两个纬度和经度之间的距离。我得到一些距离的结果,但有时,我得到的结果为NAN。

这是我在2个地方获得的纬度和经度。

例如: 38.655553,-121.091611

38.654875,-121.091324

我使用以下代码参考以下链接计算距离

Calculating distance between two geographic locations

public static double distanceBetween (double currentLat2, double currentLong2, double mallLat2, double mallLong2)
{
     float pk = (float) (180/3.14169);

        double a1 = currentLat2 / pk;
        double a2 = currentLong2 / pk;
        double b1 = mallLat2 / pk;
        double b2 = mallLong2 / pk;

        double t1 = FloatMath.cos((float) a1)*FloatMath.cos((float) a2)*FloatMath.cos((float) b1)*FloatMath.cos((float) b2);
        double t2 = FloatMath.cos((float) a1)*FloatMath.sin((float) a2)*FloatMath.cos((float) b1)*FloatMath.sin((float) b2);
        double t3 = FloatMath.sin((float) a1)*FloatMath.sin((float) b1);
        double tt = Math.acos(t1 + t2 + t3);

       return 6366000*tt;               
}

任何帮助?

感谢。

3 个答案:

答案 0 :(得分:1)

Location.distanceTo(LOcation)的文档说:

  

返回此位置与之间的近似距离(以米为单位)   给定的位置。距离是使用WGS84椭圆体定义的。

所以你可以尝试这种方式:

public static float distanceBetween (double currentLat2, double currentLong2, double mallLat2, double mallLong2) {
        Location loc1 = new Location("");
        loc1.setLatitude(currentLat2);
        loc1.setLongitude(currentLong2);

        Location loc2 = new Location("");
        loc2.setLatitude(mallLat2);
        loc2.setLongitude(mallLong2);

        return loc1.distanceTo(loc2);
}

答案 1 :(得分:1)

MathFloat以及float演员阵容是您遇到问题的原因。

我改写了,现在它起作用了,它给出了79.34m

但主要的问题是你使用了错误的公式来完成这项任务,你在这里使用了具有余弦定律的更大的圆距离公式,这对于浮点运算是众所周知的“病态条件”。然后更糟糕的是,你只使用单精度而不是双精度。

更健壮的公式是haversine公式。 它旨在克服更大的圆形公式的缺点。

此处您的原始代码已修复,(但我仍然建议使用hasrsine公式)

public void test1() {

    // 79.34253285803419
    double lat1 = 38.655553;
    double lon1 = -121.091611;

    double lat2 = 38.654875;
    double lon2 = -121.091324;

    System.out.println(distanceBetween(lat1,  lon1,  lat2,  lon2));
}

public static double distanceBetween (double currentLat2, double currentLong2, double mallLat2, double mallLong2)
{
        double pk = 180 / Math.PI;
        double a1 = currentLat2 / pk;
        double a2 = currentLong2 / pk;
        double b1 = mallLat2 / pk;
        double b2 = mallLong2 / pk;

        double t1 = Math.cos( a1) * Math.cos(a2) * Math.cos(b1) * Math.cos(b2);
        double t2 = Math.cos( a1) * Math.sin(a2) * Math.cos(b1) * Math.sin(b2);
        double t3 = Math.sin( a1) * Math.sin(b1);
        double tt = Math.acos(t1 + t2 + t3);

       return 6366000*tt;
}

答案 2 :(得分:0)

你能记录t1,t2,t3的输出吗?我感觉Math.acos()的论点超出了范围。当你可以使用Math.sinMath.cos时,也不确定为什么你不必要地投射浮动并重新加倍。

修改

使用Math.PI代替3.14169。这种近似导致了您的错误。

相关问题