简体   繁体   中英

How can i calculate the distance between two gps points in Java?

I used this code but it doesnt work:

Need the distance between two gps coordinates like 41.1212, 11.2323 in kilometers (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();
}

Longitude and latitude are given in degrees (0-360). If you want to convert degrees to radians (0-2π) you need to divide by 360 and multiply by 2π, (or equivalently, multiply by π/180 ). In your code however, you multiply by 180/π .

That is, change

double d2r = (180 / Math.PI);

into

double d2r = Math.PI / 180;

have a look a 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");

Distance is 1448.7325760822912 km

I wrote that library for one my project.

The solution from http://www.androidsnippets.com/distance-between-two-gps-coordinates-in-meter .

Only works if the points are close enough that you can omit that earth is not regular shape.

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;
}
//

see Distance between two GPS coordinates in meter .

两点之间的距离(以及许多其他有用的东西)可以在以下网址找到: http//www.movable-type.co.uk/scripts/latlong.html

The distance can be calculated with the Esri Geometry library: geodesicDistanceOnWGS84 .

I would assume that JTS also has a method for computing distance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM