I have a MySQL table in a PHP webservice containing longitude and latitude. I want to send the user only the, let\'s say, 5 closest coordinates. I wrote the method which cal
I've encountered same problem lately. What i've decided was to write a mysql function to calculate distance and then use it in sql query. Mysql function:
CREATE FUNCTION distance(lat1 float, lon1 float, lat2 float, lon2 float)
RETURNS float
RETURN ACOS(SIN(RADIANS(lat1))*SIN(RADIANS(lat2))+COS(RADIANS(lat1))*COS(RADIANS(lat2))*COS(RADIANS(lon2-lon1)))*6371
If your Coordinates
table has columns f.e. latitude
and longitude
then the code might look like this:
$q = mysql_query("SELECT * FROM Coordinates ORDER BY
distance(latitude, longitude, $lat, $lon) LIMIT 5";
Where $lat
and $lon
contain provided location.