Calculating distance between zip codes in PHP

Click Upvote picture Click Upvote · Jan 2, 2009 · Viewed 32k times · Source

I grabbed a database of the zip codes and their langitudes/latitudes, etc from this This page. It has got the following fields:

ZIP, LATITUDE, LONGITUDE, CITY, STATE, COUNTY, ZIP_CLASS

The data was in a text file but I inserted it into a MySQL table. My question now is, how can i utilise the fields above to calculate the distance between two zip codes that a user can enter on the website? Working code in PHP will be appreciated

Answer

Adam Bellaire picture Adam Bellaire · Jan 3, 2009

This is mike's answer with some annotations for the magic numbers. It seemed to work fine for me for some test data:

function calc_distance($point1, $point2)
{
    $radius      = 3958;      // Earth's radius (miles)
    $deg_per_rad = 57.29578;  // Number of degrees/radian (for conversion)

    $distance = ($radius * pi() * sqrt(
                ($point1['lat'] - $point2['lat'])
                * ($point1['lat'] - $point2['lat'])
                + cos($point1['lat'] / $deg_per_rad)  // Convert these to
                * cos($point2['lat'] / $deg_per_rad)  // radians for cos()
                * ($point1['long'] - $point2['long'])
                * ($point1['long'] - $point2['long'])
        ) / 180);

    return $distance;  // Returned using the units used for $radius.
}