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
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.
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. }
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With