I need to implement the harvesine distance in my java code.
I found this snippet in Javascript, and I need to convert it to java.
thanks
dLat = (lat2-lat1).toRad();
dLon = (lng2-lng1).toRad();
a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
Math.sin(dLon/2) * Math.sin(dLon/2);
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
d = R * c;
return d;
The Math. sin() method returns a number between -1 and 1. The Math. sin() method expects the number in radians.
The Math. cos() function returns the cosine of a number in radians.
cos() returns the trigonometric cosine of an angle. If the argument is NaN or an infinity, then the result returned is NaN. The returned value will be in range [-1, 1].
The java. lang. Math. toRadians() is used to convert an angle measured in degrees to an approximately equivalent angle measured in radians.
First of all, you should read the javadoc. sin(double) takes a double
in parameter which is the angle in radians like said in the documentation. You'll also find on the linked page that sqrt takes a double as well.
Then, you should know that java can perform non-destructive conversion automatically. So if a method takes a double and you have a long, it will be no problem, since there's no loss in the conversion long -> double. The reverse is false, so Java refuse ton compile.
For the radians conversion, you'll find a toRadians method in the Math class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With