Home > Advanced Stuff > Caclulating the distance between Zip Codes

Caclulating the distance between Zip Codes

November 18th, 2008

Calculating the distance between zip codes is not nearly as difficult as you might expect. To get started you will need two things:

  1. A zip code database that contains longitude and latitude coordindates
  2. A formula for measuring the distance between one point and another on a circle (in this case our circle is the circumference of earth)
     

You can obtain a free zip code databse from Popular Data.com, or you may wish to try the US Census Beurau. Google (and a few other companies with mapping software) also has GEO Code/Data available but make sure you check the license agreement carefully.

Once you have all your data imported into your preferred database and you have a form setup to accept a Starting and Ending Zip you need to integrate the formula into your program. Enter the Haversine formula to the rescue.

Here is a SQL implementation that works fantastic for me:

CREATE function [dbo].[geoDistance] (@lat1 decimal(9,6), @lon1 decimal(9,6), @lat2 decimal(9,6), @lon2 decimal(9,6))
returns float
as
begin
     declare @result float
     declare @r int
     declare @kmpm float
     declare @lat1R float
     declare @lat2R float
     set @kmpm = 0.621371192
     set @r = 6371
     set @lat1R = radians(@lat1)
     set @lat2R = radians(@lat2)
     set @result = acos(sin(@lat1R)*
                        sin(@lat2R)+cos(@lat1R)*
                        cos(@lat2R)*cos(radians(@lon2-@lon1)))*
                        @r*@kmpm
     if @result is null set @result = 0
     return @result
end

 

Here are some links to code in various other languages:

Caclulating the distance between Zip Codes using Python.
Caclulating the distance between Zip Codes using JavaScript.
Caclulating the distance between Zip Codes using C++.

 

*It is worth mentioning that the earth is not a perfect circle, so you should expect an inaccuracy somewhere around 2% depending upon where you are on the globe. For those who need more accuracy (about 3mm) check out the Vicenty’s Formula (which is based on the ellipsoidal model of earth).

No related posts.

Advanced Stuff ,

  1. No comments yet.
  1. No trackbacks yet.