Last Updated: September 12, 2021
·
385
· Bruno Volpato

Distance between coordinates in Java, Haversine formula

class GeoPoint {

    private static final double EARTH_RADIUS = 6372.797560856;

    double lat;
    double lon;

    public GeoPoint(double lat, double lon) {
      this.lat = lat;
      this.lon = lon;
    }

    public double distance(GeoPoint other) {

      double lat1 = Math.toRadians(this.lat);
      double lon1 = Math.toRadians(this.lon);

      double lat2 = Math.toRadians(other.lat);
      double lon2 = Math.toRadians(other.lon);

      double dlon = lon2 - lon1;
      double dlat = lat2 - lat1;
      double a = Math.pow(Math.sin(dlat / 2), 2) + Math.cos(lat1) * Math.cos(lat2) * Math.pow(Math.sin(dlon / 2), 2);

      return 2 * EARTH_RADIUS * Math.asin(Math.sqrt(a));
    }

}