PHP Sorting nearest coordinates

后端 未结 3 2015
渐次进展
渐次进展 2020-12-24 09:32

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

3条回答
  •  轮回少年
    2020-12-24 09:57

    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.

提交回复
热议问题