Home > Database > Mysql Tutorial > How to Find Points Within a Radius Using Latitude and Longitude?

How to Find Points Within a Radius Using Latitude and Longitude?

Susan Sarandon
Release: 2024-10-28 03:21:02
Original
230 people have browsed it

How to Find Points Within a Radius Using Latitude and Longitude?

Determining Proximity within a Radius Given Latitudes and Longitudes

Envision a scenario where a form allows users to input their longitude and latitude. Simultaneously, a database contains a table housing a comprehensive list of geographic coordinates. The task at hand involves identifying any points within a 15-mile radius of the user's coordinates.

Solution:

To achieve this, we leverage the concept of distance calculation between two points using a specific formula:

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));
}
Copy after login

Alternatively, a database query can be utilized:

$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.";
Copy after login

The above is the detailed content of How to Find Points Within a Radius 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