Home > Database > Mysql Tutorial > 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
Release: 2024-10-30 01:51:02
Original
987 people have browsed it

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

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

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!

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