The Haversin equation is the answer to your question. However, this is a bit difficult to decipher, so here I provide you with a simple explanation:
Simply put:
Here's an example / example of an SQL statement that will find the next 20 locations within a radius of 25 miles from coordinate 37, -122. It calculates the distance based on the latitude / longitude of this line and the target latitude / longitude (given by lat / lng in the equation below), and then it only asks for lines where the distance value is less than 25, orders the entire request by distance, and limits it to 20 results. To search by kilometers instead of miles, replace 3959 with 6371.
SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < 25 ORDER BY distance LIMIT 0 , 20;
You can convert sql to whatever you want. I mean, the principle remains the same.
Yavar source share