GPSCoordinate { @NonNull public Float calculateHaversinDistanceMeters(GPSCoordinate gpsCoordinate) { if(this.valid == GPSCoordinate.INVALID || gpsCoordinate.valid == GPSCoordinate.INVALID) { return 0f; } double EARTH_RADIUS = 6371000; double dLat = Math.toRadians(gpsCoordinate.lat - this.lat); double dLon = Math.toRadians(gpsCoordinate.lon - this.lon); double sindLat = Math.sin(dLat / 2); double sindLng = Math.sin(dLon / 2); double a = Math.pow(sindLat, 2) + Math.pow(sindLng, 2) * Math.cos(Math.toRadians(this.lat)) * Math.cos(Math.toRadians(gpsCoordinate.lat)); double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); Double distance = EARTH_RADIUS * c; return distance.floatValue(); } GPSCoordinate(double lat, double lon, @ValidGPSLocation int valid ); @NonNull Float calculateHaversinDistanceMeters(GPSCoordinate gpsCoordinate); static final int INVALID; static final int VALID; }
@Test public void testShortDistance() { GPSCoordinate coordinateA = new GPSCoordinate(46.9673220, 15.4397928, GPSCoordinate.VALID); GPSCoordinate coordinateB = new GPSCoordinate(46.9783088, 15.4341040, GPSCoordinate.VALID); assertEquals(1295.6837f, coordinateA.calculateHaversinDistanceMeters(coordinateB)); }
@Test public void testLongDistance() { GPSCoordinate coordinateA = new GPSCoordinate(-33.865143, 151.209900, GPSCoordinate.VALID); GPSCoordinate coordinateB = new GPSCoordinate(46.9783088, 15.4341040, GPSCoordinate.VALID); assertEquals(16059592.00f, coordinateA.calculateHaversinDistanceMeters(coordinateB)); }