PHP Sorting nearest coordinates

后端 未结 3 2008
渐次进展
渐次进展 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:45

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-24 10:08

    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

    0 讨论(0)
提交回复
热议问题