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
Using Google's algorithm:
$lon = //your longitude
$lat = //your latitude
$miles = //your search radius
$query = "SELECT *,
( 3959 * acos( cos( radians('$lat') ) *
cos( radians( latitude ) ) *
cos( radians( longitude ) -
radians('$lon') ) +
sin( radians('$lat') ) *
sin( radians( latitude ) ) ) )
AS distance FROM yourtable HAVING distance < '$miles' ORDER BY distance ASC LIMIT 0, 5"
latitude
and longitude
in this query are going to be your lat/lon column names.
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.
It is more efficient to embed the sort in the query.
This wonderful tutorial will help you (and provides a query that serves your needs): https://developers.google.com/maps/articles/phpsqlsearch_v3#findnearsql