MySQL Great Circle Distance (Haversine Formula)
This article addresses the challenge of calculating the great circle distance between two geographic coordinates using solely MySQL. The traditional PHP implementation, involving multiple SQL queries and complex calculations, can be cumbersome.
Solution
To convert the PHP code into pure MySQL, we leverage the Haversine formula, a mathematical equation that calculates the distance between two points on a sphere. This formula is supported by the MySQL ACOS() and RADIANS() functions.
Here's the corresponding MySQL query:
SELECT id, ( 3959 * ACOS( COS(RADIANS(37)) * COS(RADIANS(lat)) * COS(RADIANS(lon) - RADIANS(-122)) + SIN(RADIANS(37)) * SIN(RADIANS(lat)) ) ) AS distance FROM markers HAVING distance < 25 ORDER BY distance LIMIT 0, 20;
Explanation
By using this MySQL-based approach, you can efficiently calculate the great circle distance between coordinates without the need for external PHP calculations or additional SQL queries.
The above is the detailed content of How Can I Calculate Great Circle Distance Using Only MySQL?. For more information, please follow other related articles on the PHP Chinese website!