Home  >  Article  >  Database  >  How Can I Calculate the Distance Between Two Points Using Latitude and Longitude?

How Can I Calculate the Distance Between Two Points Using Latitude and Longitude?

Barbara Streisand
Barbara StreisandOriginal
2024-10-30 01:51:02869browse

How Can I Calculate the Distance Between Two Points Using Latitude and Longitude?

Calculating the Distance Between Points Using Latitude and Longitude

In numerous scenarios, it becomes necessary to determine the distance between two points given their respective latitude and longitude coordinates. A typical example involves locating points within a specific radius from a given location.

To achieve this, you can leverage mathematical formulas to calculate distances. Consider the following illustrative function:

<code class="php">function get_distance($latitude1, $longitude1, $latitude2, $longitude2, $unit = 'Mi') {
    $theta = $longitude1 - $longitude2;
    $distance = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) +
                (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) *
                cos(deg2rad($theta)));
    $distance = acos($distance);
    $distance = rad2deg($distance);
    $distance = $distance * 60 * 1.1515;
    switch($unit) {
        case 'Mi':
            break;
        case 'Km':
            $distance = $distance * 1.609344;
    }
    return (round($distance, 2));
}</code>

Alternatively, you can employ SQL queries to calculate distances within a radius using a formula like:

<code class="sql">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>

By utilizing these approaches, you can effectively search for points within a specified radius based on their latitude and longitude coordinates.

The above is the detailed content of How Can I Calculate the Distance Between Two Points Using Latitude and Longitude?. 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