11

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.

  1. How can I convert latitude and longitude to radians in Java ?
  2. Math.sin wants a double in Java. Should I pass the previously converted value in radians or not ?
  3. Math.sin and Math.cos return long. Should I declare a as long and pass it to Math.sqrt or convert it to double ?

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;
skaffman
  • 398,947
  • 96
  • 818
  • 769
aneuryzm
  • 63,052
  • 100
  • 273
  • 488

3 Answers3

7

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.

krtek
  • 26,334
  • 5
  • 56
  • 84
  • 3
    There can be a loss in the conversion long->double. For example, if the long value is an odd number above 2^53 (or below -2^53), it can't be represented exactly as a double value. For some reason, the JLS elects to ignore these conversion losses, though, and treats this conversion as a widening conversion. (Same problem for int->float and long->float - here the limit is 2^24.) – Paŭlo Ebermann Mar 05 '11 at 11:29
  • Patrick never reads the documentation for anything, instead he asks here on SO. – President James K. Polk Mar 05 '11 at 13:06
5
  1. If you have value in degrees, just do degrees * Math.PI / 180. Or better use function suggested by coobird in the comment (didn't know of it).
  2. Yes, you can pass any double value in it. (Any number, for that matter.)
  3. No, both functions take double parameter. Check the docs.
Nikita Rybak
  • 67,365
  • 22
  • 157
  • 181
2

I've found the solution here:

How can I measure distance and create a bounding box based on two latitude+longitude points in Java?

Community
  • 1
  • 1
aneuryzm
  • 63,052
  • 100
  • 273
  • 488