Caclulating the distance between Zip Codes
Calculating the distance between zip codes is not nearly as difficult as you might expect. To get started you will need two things:
- A zip code database that contains longitude and latitude coordindates
- 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:
*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).



