ZIP Code Utility

This article provides an easy method to lookup a U.S. City/State by ZIP Code, or one or more ZIP Codes by City/State. It also describes a method to calculate the distance between two ZIP Codes and find all other ZIP Codes within a radius of X miles of a specified ZIP Code.

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

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:

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.