Find features within given coordinates and distance using MySQL
Mapperz's answer is invalid. Sinus must be calculated from latitude and NOT from longitude. So corect SQL statement is:
SELECT
id, (
3959 * acos (
cos ( radians(78.3232) )
* cos( radians( lat ) )
* cos( radians( lng ) - radians(65.3234) )
+ sin ( radians(78.3232) )
* sin( radians( lat ) )
)
) AS distance
FROM markers
HAVING distance < 30
ORDER BY distance
LIMIT 0 , 20;
The SQL statement that will find the closest 20 locations that are within a radius of 30 miles to the 78.3232, 65.3234 coordinate. It calculates the distance based on the latitude/longitude of that row and the target latitude/longitude, and then asks for only rows where the distance value is less than 30 miles, orders the whole query 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(78.3232) )
* cos( radians( lat ) )
* cos( radians( lng ) - radians(65.3234) )
+ sin ( radians(78.3232) )
* sin( radians( lat ) )
)
) AS distance
FROM markers
HAVING distance < 30
ORDER BY distance
LIMIT 0 , 20;
This is using the Google Maps API v3 with a MySQL backend which your already have.
https://developers.google.com/maps/articles/phpsqlsearch_v3#findnearsql
It might be base to create a function .. so you can reuse it other other areas. Also would make your query a bit cleaner... At least that is my 2 cents.
DELIMITER $$
CREATE FUNCTION calcDistance(lat FLOAT, lng FLOAT, pnt_lat FLOAT, pnt_lng FLOAT)
RETURNS FLOAT
BEGIN
DECLARE dist FLOAT;
SET dist =
3959 * acos(
cos(radians(pnt_lat))
* cos(radians(lat))
* cos(radians(lng) - radians(pnt_lng))
+ sin(radians(pnt_lat))
* sin(radians(lat))
);
RETURN dist;
END