Calculating distance from geolocation in Java

I'm trying to measure distance from one geolocation to another in Java. On stackoverflow I came across the following post and google developer page, giving me the following formula.

6371* acos(
* cos( radians( lat ) )
* cos( radians( lng ) - radians(-122) )
+ sin( radians(37) )
* sin( radians( lat )
) )

I created the following Java code.

private static double distanceCalc(float lat, float lng) {
return 6371 * Math.acos(
Math.cos(40.84916900104506 * Math.PI / 180)
* Math.cos((lat * Math.PI / 180))
* Math.cos((lng * Math.PI / 180) - (-73.86835600032798 * Math.PI / 180))
+ Math.sin((40.84916900104506 * Math.PI / 180))
* Math.sin((lat * Math.PI / 180)));
}

but it's giving me results that are way off. The 40.84916900104506, -73.86835600032798 geolocation is in New York but I get a value returned of around ~6090 kilometers. First I thought I just entered the lat / lng in the wrong variables but that doesnt seem to be the case.

I couldnt use Math.toRadians as it asks for an integer and not a float, which will be too inaccurate so lat * Math.PI / 180 should do right? Math isn't exactly my strongest field.

• 6090km from where? – Ian Turton Apr 14 '18 at 9:52
• your code seems fine and return reasonable distances (using 40;-73 is returns 119km, the distance of about 1 degree). Check your INPUT (sign, lat-long swap). Also Math.toRadians accepts double since version 1.2 – JGH Apr 14 '18 at 17:10

This is easily accomplished using GeoTools, you can use the GeodeticCalculator to give you the distance between two points.

double distance = 0.0;

GeodeticCalculator calc = new GeodeticCalculator(crs);
calc.setStartingGeographicPoint(points.getX(), points.getY());
calc.setDestinationGeographicPoint(points.getX(), points.getY());

distance = calc.getOrthodromicDistance();
double bearing = calc.getAzimuth();

Measure<Double, Length> dist = Measure.valueOf(distance, SI.METER);
System.out.println(dist.doubleValue(SI.KILOMETER) + " Km");
System.out.println(dist.doubleValue(NonSI.MILE) + " miles");
System.out.println("Bearing " + bearing + " degrees");

So for example the distance between New York (40.7128° N, 74.0060° W) and Los Angeles (34.0522° N, 118.2437° W) is

3944.422231489921 Km 2450.9503446683375 miles Bearing -86.26750767247016 degrees