Java Geolocation – Calculating Distance from Geolocation in Java

distancegeolocationjava

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(37) ) 
* 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.

Best Answer

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[0].getX(), points[0].getY());
    calc.setDestinationGeographicPoint(points[1].getX(), points[1].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