Home  >  Article  >  Database  >  How to Calculate Distances within a Radius Using Latitude and Longitude in PHP?

How to Calculate Distances within a Radius Using Latitude and Longitude in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-10-30 18:40:03530browse

How to Calculate Distances within a Radius Using Latitude and Longitude in PHP?

Calculating Distances from Latitude and Longitude

In this scenario, you're looking to determine the points within a 15-mile radius of the user-entered coordinates. To achieve this, you can leverage mathematical formulas to calculate distances.

Consider the following PHP function:

<code class="php">function get_distance($latitude1, $longitude1, $latitude2, $longitude2, $unit = 'Mi') { 

    // Calculate the angle difference
    $theta = $longitude1 - $longitude2; 

    // Calculate the distance
    $distance = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + 
                (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * 
                cos(deg2rad($theta))); 

    // Convert to degrees
    $distance = acos($distance); 
    $distance = rad2deg($distance); 

    // Convert to miles or kilometers
    $distance = $distance * 60 * 1.1515; 

    // Round the distance
    return (round($distance,2));
}</code>

Alternatively, you can utilize a database query to accomplish this:

<code class="sql">$query = "SELECT *,(((acos(sin((".$latitude."*pi()/180)) * 
            sin((`Latitude`*pi()/180))+cos((".$latitude."*pi()/180)) * 
            cos((`Latitude`*pi()/180)) * cos(((".$longitude."- `Longitude`)* 
            pi()/180))))*180/pi())*60*1.1515
        ) as distance 
        FROM `MyTable` 
        HAVING distance > ".$distance.";</code>

The above is the detailed content of How to Calculate Distances within a Radius Using Latitude and Longitude in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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