Ord’s Blog
RSS icon Home icon
  • Distance betwen points in Java

    Posted on February 19th, 2009 Ord 1 comment

    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.

     

    One response to “Distance betwen points in Java”


    1. CheapTabletsOnline.Com. Canadian Health&Care.No prescription online pharmacy.Best quality drugs.Special Internet Prices. Online Pharmacy. Order pills online

      Buy:VPXL.Tramadol.Soma.Levitra.Viagra Soft Tabs.Viagra Super Active+.Cialis Super Active+.Cialis Soft Tabs.Cialis.Viagra.Viagra Super Force.Zithromax.Propecia.Super Active ED Pack.Cialis Professional.Viagra Professional.Maxaman….

    Leave a reply

    Spam protection by WP Captcha-Free