Implements the Haversine formula to calculate the distance between two points on a sphere.
The formula allows to compute the haversine of θ (that is, hav(θ)) from the latitude (represented by φ) and longitude (represented by λ) of the two points:
Where:
- φ1, φ2 are the latitude of point 1 and latitude of point 2,
- λ1, λ2 are the longitude of point 1 and longitude of point 2.
Add the dependency if you are using Maven:
<dependency>
<groupId>dev.loqo71la</groupId>
<artifactId>haversine</artifactId>
<version>1.0</version>
</dependency>
Or if you are using Gradle:
implementation group: 'dev.loqo71la', name: 'haversine', version: '1.0'
To get the distance between two points, you can use the static method calculateDistance(Coordinate source, Coordinate target)
.
Haversine.calculateDistance(40.6892, 74.0445);
By default Kilometers is the unit of measure, but you can also use Meters and Miles.
Haversine.calculateDistance(40.6892, 74.0445, Unit.Kilometers);
Haversine.calculateDistance(40.6892, 74.0445, Unit.Meters);
Haversine.calculateDistance(40.6892, 74.0445, Unit.Miles);