Home > Database > Mysql Tutorial > body text

How to Calculate Distance Between Two Points Using Latitude and Longitude?

Barbara Streisand
Release: 2024-10-29 01:56:02
Original
218 people have browsed it

How to Calculate Distance Between Two Points Using Latitude and Longitude?

Calculating Distance Given Two Points: Latitude and Longitude

Determining the distance between points using their latitude and longitude is a common GIS task. To find points within a specified radius, we can leverage mathematical formulas and SQL queries.

Formula for Distance Calculation

One approach is to use the Haversine formula, which calculates the distance between two points on a sphere:

<code class="python">def get_distance(lat1, lon1, lat2, lon2, unit='Mi'):
    theta = lon1 - lon2
    distance = (math.sin(math.radians(lat1)) * math.sin(math.radians(lat2))) + \
              (math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * \
              math.cos(math.radians(theta)))
    distance = math.acos(distance)
    distance = math.degrees(distance)
    distance = distance * 60 * 1.1515
    if unit == 'Km':
        distance = distance * 1.609344
    return round(distance, 2)</code>
Copy after login

SQL Query for Radius Search

Another option is to use a MySQL query with the distance formula:

<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 applying these methods, you can efficiently calculate the distance between points and find those within a desired radius from a given location.

The above is the detailed content of How to Calculate 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!