Java Distance Calculate distance(double lat1, double lng1, double lat2, double lng2)

Here you can find the source of distance(double lat1, double lng1, double lat2, double lng2)

Description

Calculate distance (in meters) between two points in (latitude, longitude).

License

Open Source License

Declaration

public static double distance(double lat1, double lng1, double lat2, double lng2) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    public static final double LATITUDE_MAX = 90.0;
    public static final double LONGITUDE_MAX = 180.0;

    /**/* w  ww.j  a v a2s  . c om*/
     * Calculate distance (in meters) between two points in (latitude, longitude).
     * <p>
     * Uses Haversine method to compute the distances.
     * If (lat, long) combination are invalid it returns a negative distance (invalid value)
     * </p>
     * Taken from : http://stackoverflow.com/a/27943
     */
    public static double distance(double lat1, double lng1, double lat2, double lng2) {
        if (Math.abs(lat1) == LATITUDE_MAX || Math.abs(lat2) == LATITUDE_MAX || Math.abs(lng1) == LONGITUDE_MAX
                || Math.abs(lng2) == LONGITUDE_MAX) {
            return Double.MAX_VALUE;
        }

        final int R = 6371;// Radius of the earth

        Double dLat = Math.toRadians(lat2 - lat1);
        Double dLon = Math.toRadians(lng2 - lng1);
        double sinLatDist = Math.sin(dLat / 2);
        double cosLat1 = Math.cos(Math.toRadians(lat1));
        double cosLat2 = Math.cos(Math.toRadians(lat2));
        double sinLonDist = Math.sin(dLon / 2);

        Double a = (sinLatDist * sinLatDist) + (cosLat1 * cosLat2 * sinLonDist * sinLonDist);
        Double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        return R * c * 1000;// convert to meters
    }
}

Related

  1. dist14(double d12, double d23, double d34, double theta123, double theta234, double phi)
  2. dist2Degrees(double dist, double radius)
  3. dist2Radians(double dist, double radius)
  4. distAlongRaySquared(double px, double py, double qx, double qy, double rx, double ry)
  5. distance(double lat1, double lng1, double lat2, double lng2)
  6. distance(double lat1, double lon1, double lat2, double lon2)
  7. distance(double lat1, double lon1, double lat2, double lon2)
  8. distance(double lat1, double lon1, double lat2, double lon2)
  9. distance(double lat1, double lon1, double lat2, double lon2)