Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating distance between zip codes in PHP

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

like image 896
Ali Avatar asked Jan 02 '09 20:01

Ali


People also ask

How do you find the distance between two Geocodes?

The distance difference in the longitude direction is EarthRadius * longitude difference * cos(latitude) . We multiply by cos(lat) because the longitude degrees don't make the same km distance if the latitude changes. As P1 and P2 are close, cos(latP1) is close from cos(latP2) Then Pythagore.


2 Answers

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. } 
like image 144
2 revs, 2 users 95% Avatar answered Sep 23 '22 07:09

2 revs, 2 users 95%


It can be done with just maths...

function calc_distance($point1, $point2)
{
    $distance = (3958 * 3.1415926 * sqrt(
            ($point1['lat'] - $point2['lat'])
            * ($point1['lat'] - $point2['lat'])
            + cos($point1['lat'] / 57.29578)
            * cos($point2['lat'] / 57.29578)
            * ($point1['long'] - $point2['long'])
            * ($point1['long'] - $point2['long'])
        ) / 180);

    return $distance;
}
like image 24
Mike Paterson Avatar answered Sep 21 '22 07:09

Mike Paterson