Postgres: Search and Sort by Radial Distance
Request users by radial distance and sort by nearest to farthest, vice versa, or whatever other attributes you’d like to include.
Searching for a user by distance, in your database, is easy with Postgres. Just create a users table with, at minimum, columns named latitude and longitude.
Data
1 2 3 4 |
|
SQL
1 2 3 4 5 6 |
|
Matches all users WHERE distance <= 5
(less than or equal to five miles).
To change the distance to kilometers—multiply the output number by 1.609344 (1 mile == 1.609344 kilometers).
Replace #{latitude}
with the value for the latitude you want to match against the database and do the same for #{longitude}
This will work in any SQL relational database, including MySQL and Oracle.