Skip to content

Instantly share code, notes, and snippets.

@Thivieira
Forked from statickidz/nearby-coordinates.sql
Created April 19, 2018 03:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Thivieira/d7e092cc07741e0f7deb8184ef921be2 to your computer and use it in GitHub Desktop.
Save Thivieira/d7e092cc07741e0f7deb8184ef921be2 to your computer and use it in GitHub Desktop.
Ordering with SQL by nearest latitude & longitude coordinates (MySQL & SQLite)
---
METHOD 1
This should roughly sort the items on distance in MySQL, and should work in SQLite.
If you need to sort them preciser, you could try using the Pythagorean theorem (a^2 + b^2 = c^2) to get the exact distance.
---
SELECT *
FROM table
ORDER BY ((lat-$user_lat)*(lat-$user_lat)) + ((lng - $user_lng)*(lng - $user_lng)) ASC
---
METHOD 2
---
SELECT
id, (
6371 * acos (
cos ( radians($user_lat) )
* cos( radians( lat ) )
* cos( radians( lng ) - radians($user_lng) )
+ sin ( radians($user_lat) )
* sin( radians( lat ) )
)
) AS distance
FROM table
HAVING distance < 30
ORDER BY distance
LIMIT 0 , 20;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment