Home > Database > Mysql Tutorial > How to Calculate the Distance Between Two Zip Codes in PHP?

How to Calculate the Distance Between Two Zip Codes in PHP?

DDD
Release: 2024-11-02 11:44:30
Original
467 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template