DomeWTF DomeWTF - 1 year ago 59
MySQL Question

How to filter database results by nearness of gps location?

I'm getting a GPS location via an android app and then asking the server which of the records in the database are near it.

How can I accomplish this?

Let's say that these are the coordinates:

39.017411, -97.251117

How can I ask the database in PHP to only give me the results that contain coordinates near those?

Answer Source

You can do something like as mentioned below, considering field name of your table is lat for latitude and lng for longitude

$lat = 39.017411;
$lng = -97.251117;

    $result=mysql_query("SELECT,, tbl.lng, 111.045 * DEGREES(ACOS(COS(RADIANS($lat))
 * COS(RADIANS(lat))
 * COS(RADIANS(lng) - RADIANS($lng))
 + SIN(RADIANS($lat))
 * SIN(RADIANS(lat))))
 AS distance_in_km
FROM table_name as tbl
ORDER BY distance_in_km ASC
LIMIT 0,1");
        echo $row[lat].";".$row[lng];