Home > Database > Mysql Tutorial > How to Calculate the Distance Between Two Points Using Latitude and Longitude in MySQL?

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

Linda Hamilton
Release: 2024-12-18 12:05:20
Original
608 people have browsed it

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

Calculating Distance Between Two Points Using Latitude and Longitude in MySQL

To determine the distance between two points given their latitude and longitude, MySQL provides a powerful formula. In this scenario, one user is located in city 3 and seeks to find the distance to users in other cities, such as city 7.

The solution lies in utilizing the following query:

SELECT a.city AS from_city, b.city AS to_city, 
   111.111 *
    DEGREES(ACOS(LEAST(1.0, COS(RADIANS(a.Latitude))
         * COS(RADIANS(b.Latitude))
         * COS(RADIANS(a.Longitude - b.Longitude))
         + SIN(RADIANS(a.Latitude))
         * SIN(RADIANS(b.Latitude))))) AS distance_in_km
  FROM city AS a
  JOIN city AS b ON a.id <> b.id
 WHERE a.city = 3 AND b.city = 7
Copy after login

This query employs the spherical cosine law formula, which calculates the distance in kilometers between two points on a sphere. It joins the table to itself, allowing the retrieval of two coordinate pairs for computation.

The result of this query will provide the distance between city 3 and city 7 in kilometers. To obtain the distance in statute miles, simply replace the constant 111.1111 with 69.0.

For efficiency in locating nearby points, consider using the ST_Distance_Sphere function:

select ST_Distance_Sphere(
    point(-87.6770458, 41.9631174),
    point(-73.9898293, 40.7628267)) 
Copy after login

Alternatively, bounding box computation can be employed to further optimize the search.

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