﻿ ODM Technology » Distance betwen points in Java

# Distance betwen points in Java

I needed to calculate the distance between two postals codes, in the case where I have latitude and longitude for each one.  It took some searching around the net to find the right formula, although along the way I found dozens of pages that would calculate the distances for me.

The method milesBetween in my ZipCode class reports the number of miles between this Zip Code and the supplied argument.

```double milesBetween(ZipCode zip){ double distance; distance = ( 3958 * Math.PI * Math.sqrt( (this.latitude - zip.latitude) * (this.longitude - zip.longitude) + Math.cos( Math.toRadians(this.latitude)) * Math.cos( Math.toRadians(zip.latitude)) * ( (this.longitude - zip.longitude) * (this.longitude - zip.longitude) ) )/180);   return distance; }```

The constant 3958 is the (average) radius of the earth in miles.  Chaging to 6369 would give us the distances in Kilometers instead.

Posted on February 19, 2009 at 9:45 am by Ord · Permalink
In: Uncategorized