0

我正在使用此代码来计算两点之间的距离。我正在使用 Haversine 公式

private double CalcDistance(Location Start, Location End) 
    {
        // TODO Auto-generated method stub
        double distance;
        double lat1 = Start.getLatitude();
        double lat2 = End.getLatitude();
        double lng1 = Start.getLongitude();
        double lng2 = End.getLongitude();
        double dLat = Math.abs(Math.toRadians(lat2-lat1));
        double dLng = Math.abs(Math.toRadians(lng2 - lng1));

        distance = Math.sin(dLat/2) * Math.sin(dLng/2) + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * 
                Math.sin(dLng/2) * Math.sin(dLng/2);

        double c = 2 * Math.asin(Math.sqrt(distance));

        //Return the answer in Kilometre (6371km the mean radius of the earth)
        return c * 6371;
    }

仅当位置的经度更改时生成的值才会更改,如果纬度更改则保持不变。有什么理由我的代码只这样做。

4

2 回答 2

1

你需要改变

Math.sin(dLat/2) * Math.sin(dLng/2)

Math.sin(dLat/2) * Math.sin(dLat/2)
于 2012-02-10T00:09:16.900 回答
1

嘿我不完全确定,但只是看看你的代码你可能犯了一个错误,我不明白,但也许你可以改变

distance = Math.sin(dLat/2) * Math.sin(dLng/2) + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * 
                Math.sin(dLng/2) * Math.sin(dLng/2);

distance = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * 
                Math.sin(dLng/2) * Math.sin(dLng/2);
于 2012-02-10T00:10:33.013 回答