我该如何在Java中计算两个GPS点之间的距离?

22

我用了这段代码,但是它没有工作:

需要计算两个GPS坐标之间的距离,例如41.1212, 11.2323,单位为公里(Java)

double d2r = (180 / Math.PI);
double distance = 0;

try{
    double dlong = (endpoint.getLon() - startpoint.getLon()) * d2r;
    double dlat = (endpoint.getLat() - startpoint.getLat()) * d2r;
    double a =
        Math.pow(Math.sin(dlat / 2.0), 2)
            + Math.cos(startpoint.getLat() * d2r)
            * Math.cos(endpoint.getLat() * d2r)
            * Math.pow(Math.sin(dlong / 2.0), 2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    double d = 6367 * c;

    return d;

} catch(Exception e){
    e.printStackTrace();
}

3
如果地球是一个完美的球体,你的三角学方法会非常有效。然而,事实上它是一个椭球体,因此从表面到地心的半径取决于你在地球上的位置而有所变化。为了获得精确的距离测量值,你需要使用一个能够考虑到这一点的坐标系统库。假设一个球体对于你正在进行的任何事情来说已经足够接近了,但如果你需要非常精确的结果,你需要找到一个好的库。 - A. Levy
重复自:https://dev59.com/I3A65IYBdhLWcg3wrQl4 - gonella
6个回答

20

经度和纬度以度数(0-360)给出。如果您想将度数转换为弧度(0-2π),则需要除以360并乘以2π(或等效地,乘以 π/180)。但在您的代码中,您是将其乘以 180/π

也就是说,请将

double d2r = (180 / Math.PI);

转换为

double d2r = Math.PI / 180;

11

看一下Geocalc

Coordinate lat = new GPSCoordinate(41, .1212);
Coordinate lng = new GPSCoordinate(11, .2323);
Point point = new Point(lat, lng);

lat = new DegreeCoordinate(51.4613418);
lng = new DegreeCoordinate(-0.3035466);
Point point2 = new Point(lat, lng);
System.out.println("Distance is " + EarthCalc.getDistance(point2, point) / 1000 + " km");

距离为1448.7325760822912公里

我为我的一个项目编写了那个库。


8

这是从http://www.androidsnippets.com/distance-between-two-gps-coordinates-in-meter获取的解决方案。

仅在两点足够接近以至于可以省略地球不是规则形状时才有效。

private double gps2m(float lat_a, float lng_a, float lat_b, float lng_b) {
    float pk = (float) (180/3.14169);
float a1 = lat_a / pk; float a2 = lng_a / pk; float b1 = lat_b / pk; float b2 = lng_b / pk;
float t1 = FloatMath.cos(a1)*FloatMath.cos(a2)*FloatMath.cos(b1)*FloatMath.cos(b2); float t2 = FloatMath.cos(a1)*FloatMath.sin(a2)*FloatMath.cos(b1)*FloatMath.sin(b2); float t3 = FloatMath.sin(a1)*FloatMath.sin(b1); double tt = Math.acos(t1 + t2 + t3);
return 6366000*tt; } //

请参见Distance between two GPS coordinates in meter


2


0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接