Skip to content

Instantly share code, notes, and snippets.

@samuel-alves
Last active November 19, 2019 10:21
Show Gist options
  • Save samuel-alves/a85a51682364e33aecdaf6390ae64c15 to your computer and use it in GitHub Desktop.
Save samuel-alves/a85a51682364e33aecdaf6390ae64c15 to your computer and use it in GitHub Desktop.
PostgreSQL function to calculate the distance between to points in a spherical surface.
CREATE OR REPLACE FUNCTION haversine(latitude1 numeric(10,6),longitude1 numeric(10,6), latitude2 numeric(10,6), longitude2 numeric(10,6))
RETURNS double precision AS
$BODY$
SELECT 3959 * acos( cos( radians(latitude1) ) * cos( radians( latitude2 ) ) * cos( radians( longitude1 ) - radians(longitude2) ) + sin( radians(latitude1) ) * sin( radians( latitude2 ) ) ) AS distance
$BODY$
LANGUAGE sql;
/*
SELECT id,
name,
latitude__c,
longitude__c,
haversine(40.5378408, -7.2662964, a.latitude__c::numeric, a.longitude__c::numeric) AS distance
FROM
public.example AS ex WHERE (longitude__c IS NOT NULL AND latitude__c IS NOT NULL) ORDER BY distance ASC;
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment