Home > Database > Mysql Tutorial > body text

How to Calculate Distance Between Two Zip Codes in PHP?

Patricia Arquette
Release: 2024-11-02 07:38:29
Original
790 people have browsed it

How to Calculate Distance Between Two Zip Codes in PHP?

Determining Distance Between Zip Codes in PHP

A user's request to calculate the distance between two zip codes necessitates utilizing a database of zip codes and their corresponding latitudes and longitudes. This guide provides a solution in PHP based on the provided data fields:

Solution:

To calculate the distance between two zip codes, the following steps can be taken:

  1. Join the latitude and longitude values of the two zip codes using the defined database fields (LATITUDE and LONGITUDE) for each zip code.
  2. Calculate the Haversine distance using the following formula:
<code class="php">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.
}</code>
Copy after login

This code utilizes the Earth's radius constant (3958 miles) and converts the latitude and longitude values to radians for accurate distance calculation.

The above is the detailed content of How to Calculate 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!