Home >Database >Mysql Tutorial >How to Calculate the Distance Between Two Zip Codes in PHP?
Calculating Distance Between Zip Codes in PHP
Calculating the distance between two zip codes requires accessing a database containing latitude and longitude information for each zip code. This question explores how to compute this distance using data from a MySQL table.
SOLUTION
The suggested solution leverages a PHP function to calculate the distance between two points given their latitudes and longitudes. Here's the code:
<code class="php">function calc_distance($point1, $point2) { // Constants $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 to radians for cos() * cos($point2['lat'] / $deg_per_rad) // Convert to radians for cos() * ($point1['long'] - $point2['long']) * ($point1['long'] - $point2['long']) ) / 180); return $distance; // Returned using the units used for $radius. }</code>
USAGE
This function requires two data points ($point1 and $point2) as parameters, each containing the latitude and longitude of a zip code. The returned distance will be in the same units as the radius constant provided (miles in this case).
The above is the detailed content of How to Calculate the Distance Between Two Zip Codes in PHP?. For more information, please follow other related articles on the PHP Chinese website!