phpiosmysqlgoogle-maps

How can I do to return places in distance order


I have a database full of places (lets say more than 50) with their address. And from an APP they send me their location and I have to return the places order by the ones that are closer to the location they send me. Do I have to do a Google Maps API call every time, and for the 50, to know? Or there is another way, with better performance?


Solution

  • I'll assume that your database is MySQL and that you have the latitude and longitude for the stored places.

    You can do a Geospatial search using SQL queries. For example this one

    set @orig_lat=122.4058;
    set @orig_lon=37.7907;
    
    SELECT *, 3956 * 2 * ASIN(SQRT( POWER(SIN((@orig_lat - abs(dest.lat)) * pi()/180 / 2),2) + COS(@orig_lat * pi()/180 ) * COS(abs(dest.lat) *  pi()/180) * POWER(SIN((@orig_lon – dest.lon) * pi()/180 / 2), 2) )) as distance
    FROM Places dest
    ORDER BY distance;
    

    That assumes that you have the lat and lon columns and will get the places from the database and order them by distance.

    Take a look to this presentation as reference andd to understand the calculations http://es.scribd.com/doc/2569355/Geo-Distance-Search-with-MySQL