L'elegante (più accurato ) modo per farlo (ma non velocissimo )
// Closest within radius of 25 Miles
// 37, -122 are your current coordinates
// To search by kilometers instead of miles, replace 3959 with 6371
SELECT feature_name,
( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) )
* cos( radians( long ) - radians(-122) ) + sin( radians(37) )
* sin( radians( lat ) ) ) ) AS distance
FROM geo_features HAVING distance < 25
ORDER BY distance LIMIT 1;
Modifica
Questa è la formula Haversine per il calcolo della distanza circolare dalle coordinate geografiche. Ecco alcune implementazioni di questa formula in diverse piattaforme
R = earth’s radius (mean radius = 6,371km)
Δlat = lat2− lat1
Δlong = long2− long1
a = sin²(Δlat/2) + cos(lat1).cos(lat2).sin²(Δlong/2)
c = 2.atan2(√a, √(1−a))
d = R.c
// Note that angles need to be in radians to pass to Trigonometric functions