Skip to content

Instantly share code, notes, and snippets.

@jamesduncombe
Last active August 29, 2015 14:11
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 jamesduncombe/61b3f525bd5e1f2a68c7 to your computer and use it in GitHub Desktop.
Save jamesduncombe/61b3f525bd5e1f2a68c7 to your computer and use it in GitHub Desktop.
Haversine formula in SQL
/*
6371 for Kms
3956 for Miles
$lat, $lng are passed in
*/
SELECT *,
( 3956 * acos( cos(radians($lat)) * cos(radians( lat.field_latitude_value )) *
cos(radians( lng.field_longitude_value ) - radians($lng)) + sin(radians($lat))
* sin(radians( lat.field_latitude_value )) ) )
AS distance_in_miles
FROM table_name
/* Override distance in mile as needed */
HAVING distance_in_miles < 50
WHERE "listings"."status" IN ('Open')
ORDER BY distance_in_kilometres, created_at DESC
LIMIT 0, 10
/* See: http://www.codecodex.com/wiki/Calculate_Distance_Between_Two_Points_on_a_Globe#PostgreSQL_PL.2FPERLU */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment