简体   繁体   中英

Calculate the distance between two Geographical Coordinates in Java

I have two GPS Coordinates, for example: (44.40239182909422, 8.930511474608954) and (30.297017883371236, 122.3822021484364)

I would like to know the distance in meters between these two points. I don't know if the first coordinate is greater than the second or not.

I am trying to understand and modify this code example:

 private double _distance(double lat1, double lon1, double lat2, double lon2) {
      double theta = lon1 - lon2;
      double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
      dist = Math.acos(dist);
      dist = rad2deg(dist);
      dist = dist * 60 * 1.1515; // 60 is the number of minutes in a degree;  //1.1515 is the number of statute miles in a nautical mile.One nautical mile is the length of one minute of latitude at the equator.
      dist = dist * 1.609344;

      return (dist);
}

To calculate the 'theta' I added the following code:

double theta = lon1 - lon2;

if(lon2>lon1)
    theta = lon2 - lon1;

The distance function will return the distance between two points in meteres

public double distance() {

    double lat1 = 44.40239182909422;
    double lon1 = 8.930511474608954;
    double lat2 = 30.297017883371236;
    double lon2 = 122.3822021484364;
    double theta = lon1 - lon2;
    double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
    dist = Math.acos(dist);
    dist = rad2deg(dist);
    dist = dist * 1.609344 * 1000;        
    return (dist); // 134910.69784909734
}
    /* The function to convert decimal into radians */
private double deg2rad(double deg) {
    return (deg * Math.PI / 180.0);
}       
    /* The function to convert radians into decimal */
private double rad2deg(double rad) {
    return (rad * 180.0 / Math.PI);
}

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