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.