Click here to Skip to main content
Click here to Skip to main content

ZIP Code Utility

By , 2 Jan 2005
 

Introduction

Intrigued by Ben Fry's zipdecode [^] applet, I decided to write a little ZIP Code utility that allows lookups of U.S. locations by ZIP Code, City/State, or all three. Since the data were already in the database in the form of latitude/longitude pairs, I added the capability to find the distance between two points, and to find all other ZIP Codes within a radius of X miles from the original location.

Background

Database

The MS Access database contains the following fields:

Field Name Description
ZIP The ZIP Code
LATITUDE Latitude coordinate (decimal degrees)
LONGITUDE Longitude coordinate (decimal degrees)
CITY City name
STATE State abbreviation
COUNTY County name
ZIP_CLASS ZIP Code class

ZIP Code — City/State lookups

The lookups are straightforward database queries using the OleDb* classes.

Distance calculation

To calculate the distance between two points, I used the Haversine Formula, which I found on the Ask Dr. Math web site.

ZIP Codes within a radius of X miles

Most ZIP Codes in the database contain latitude/longitude coordinates. To make the SQL query as simple as possible, I used a square of size 2Rx2R (where R is the radius of the circle) to encompass the search area as shown in the figure below.

This has the unfortunate side effect of searching an area ~22% larger than needed, but these "outliers" are filtered out of the result set on the client side before being returned to the calling application. I could have added a stored procedure to perform the distance calculation, but I didn't want to modify the database in any way. That way, if the author decides to update the data, (hopefully) all the users of this library will have to replace the old database file with the new one.

Now, using this approximation, the SQL query becomes as simple as this:

SELECT * 
FROM ZIP_CODES 
WHERE
    LATITUDE >= <Southern Latitude Line> AND 
    LATITUDE <= <Northern Latitude Line> AND 
    LONGITUDE >= <Western Longitude Line> AND
    LONGITUDE <= <Eastern Longitude Line>

To calculate the Northern/Southern Latitude and Western/Eastern Longitude lines, I again turned to Ask Dr. Math.

Important classes

Class Name Description
ZipCodeUtil The ZipCodeUtil class provides methods to lookup City/State by ZIP Code, or ZIP Code by City/State.
Location A Location represents a City, State, ZIP Code, County, Latitude, Longitude, and ZIP Class. This just so happens to correspond to the columns of the ZIP_CODES table.
LocationInRadius Derives from Location, and adds the DistanceToCenter property.
Distance The Distance class' static GetDistance method takes two Location objects and uses their Latitudes and Longitudes to determine the distance between them.
Radius Provides a static method that takes a Location and a radius (in miles), and returns the LocationInRadiuses that fall within that radius.

Using the code

Using the code is very straightforward.

  1. Download the ZIP Codes database (see link at top of article).
  2. Compile the ZipCodeUtil library in VS.NET.
  3. Add a reference to the new DLL (SagaraSoftware.ZipCodeUtil.dll) to your application.
  4. Add the following appSettings to your application's config file (you'll need to add a config file if one doesn't already exist):
    <add key="ZipCodeProviderType" value="Access" />
    <add key="ZipCodeConnString" value=
    "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=
              D:\Example\Path\To\Database\zipbase.mdb" />
  5. Add code to use the ZIP Code Utility library.

Here is the sample code from the example application:

(Note that in order to run the sample application, you'll first need to download the database and modify the config file to point to the database on your hard disk.)

//    Location by ZIP Code.
Location location = ZipCodeUtil.LookupByZipCode ("93275");
if (null != location)
    Console.WriteLine (location.ToString ());

//    Location(s) by City/State.
Location[] locs = ZipCodeUtil.LookupByCityState ("Tulare", "CA");
if (null != locs && locs.Length > 0)
{
    foreach (Location loc in locs)
    {
        Console.WriteLine (loc.ToString ());
    }
}

//    Location by City/State/Zip
location = ZipCodeUtil.LookupByCityStateZip ("Tulare", "CA", "93275");
if (null != location)
    Console.WriteLine (location.ToString ());

//    Distance between two locations.
Location sf = ZipCodeUtil.LookupByZipCode ("94175");
Location la = ZipCodeUtil.LookupByZipCode ("90185");
Double dDistance = sf.DistanceFrom (la);
Console.WriteLine ("{0} is {1} miles from {2}", sf.City, dDistance, la.City);

//    Other Locations within an X-mile radius of a specific location.
locs = sf.LocationsWithinRadius (5.0);
if (null != locs && locs.Length > 0)
{
    foreach (Location loc in locs)
    {
        Console.WriteLine (loc.ToString ());
    }
}

Limitations

This library relies on data from a free database that doesn't look like it has been updated since September 2001. I cannot vouch for the accuracy of this data. If you plan on using this in a production environment, you may want to invest in a commercial ZIP Codes database that is guaranteed by its maker and that is updated regularly.

To do List

  • Pending approval from the creator of the database, provide MS SQL and MySQL versions.

History

  • 2nd Jan 2005 - Version 1.0.0
    • Initial release.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Jon Sagara
Software Developer (Senior) Sagara Software, Inc.
United States United States
Member
Jon graduated from Cal Poly with a B.S. Computer Engineering. He is currently building a Silverlight-based report scheduling interface for a pharmaceutical reporting company.
 
When he's not fooling around with computers or reading, he's busy spending time with his super wife, Kelly, his two boys, and their rambunctious dog, Homer.
 
Visit my blog
 
---
 
View my old profile pictures

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5membermanoj kumar choubey12 May '13 - 23:32 
Nice
Questionzip code radiusmemberPeter Hammer7 May '13 - 0:56 
Here you can find the open sources codes for the zip code radius calculation in PHP, ASP.NET (C#) and Coldfusion: http://www.zipcodesoft.com/zip-codes-in-a-radius
You can also calculate the distance as the road distance instead of beeline distance: http://www.zipcodesoft.com/distance-between-zip-codes
The necessary zip code database you can download here: http://www.zipcodesoft.com
GeneralIts really gr8 articlememberDotNetGuts30 Aug '08 - 16:51 
Hey its really good article i have enjoyed it.
 
Thanks for posting such a informative article, it had save my lot of time.
 
I have also blog your work.
http://dotnetguts.blogspot.com/2008/08/finding-distance-based-on-zipcode-or.html[^]
 
DotNetGuts
"Lets Make Programming Easy"
 
Logon to http://www.dotnetguts.blogspot.com
Join .Net Developer's Community http://groups.yahoo.com/group/dotnetguts/join

GeneralZip Code Radius Search Solutionmembercodezilla9412 Nov '07 - 14:13 
check this out. This solution contains a Stored Procedure that accepts a zip code and mile radius and returns all zip codes within that radius. (Example: Give me all the zip codes within a 10-mile radius of 50325). The Solution comes with and a dataload script that will create a SQL Server database, the Stored Procedure containing the algorithm, and load over 42,00 zip codes.
 
http://www.spikesolutions.net/ViewSolution.aspx?ID=1e7d197c-7441-40f4-8e87-5ecc3ef5ab60
GeneralRe: Zip Code Radius Search SolutionmemberJon Sagara12 Nov '07 - 15:31 
Please don't spam the message boards. If you wish to advertise your product, contact the owners of this site:
 
http://www.codeproject.com/info/MediaKit/[^]
 
Jon Sagara
 
Once again, the conservative sandwich-heavy portfolio pays off for the hungry investor! *slurp* Oh, I'm ruined!
 
-- Dr. Zoidberg

 
.NET Blog | Personal Blog | Articles

QuestionMissing Databasememberellios5 Dec '06 - 1:55 
The database in the in the link is actually unavaliable on from the site that you have specified, the .mdb is not zipped up and is forbidded from being accessed by asp.net due to if file type. Does anyone have a local copy of the DB that they can upload?
AnswerRe: Missing Database [modified]memberJon Sagara5 Dec '06 - 4:11 
Try emailing the site owner to see if s/he can fix that.
 
novak at linenoize dot com
 
The page is over 5 years old, so hopefully it's still a valid address.
 
Or use the company's main contact page: http://www.cfdynamics.com/cfdynamics/contactus.cfm[^]
 
If that fails, you can purchase a commercial database. You'll need to modify the code a bit, but the concepts are still the same.
 
http://www.zipcodedownload.com/[^]
 
Or, alternatively, since the text version is still available, you could just import it really quickly into an Access DB.
 

-- modified at 10:16 Tuesday 5th December, 2006
 
Jon Sagara
When I grow up, I'm changing my name to Joe Kickass!
My Blog | My Site | My Articles

SuggestionRe: Missing Databasemembermarsh wiggle5 Dec '12 - 10:43 
You can get a free zip code database here that is kept pretty up-to-date: greatdata.com/free-zip-code-database
GeneralGUI, GUI, GUImemberBassam Abdul-Baki9 May '06 - 3:34 
Guid job. That's a very useful application and I'm glad some gui decided to write it. But I feel that there's something missing or disGUIsed. Smile | :)
 
There are II kinds of people in the world. Those who understand binary and those who understand Roman numerals. Web - Blog - RSS - Math
QuestionStuffing data in a DLL?memberHyperX15 Feb '06 - 6:32 
Hello,
 
I was just wondering if its possible to stream all the info in the access db into a stream and stuffing it in a DLL for later use, instead of calling a database etc.?
 
Thanks, Sniff | :^)
 
HyperX.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 2 Jan 2005
Article Copyright 2005 by Jon Sagara
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid