Skip to content

Instantly share code, notes, and snippets.

@carlzulauf
Created February 2, 2012 16:47
Show Gist options
  • Star 29 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save carlzulauf/1724506 to your computer and use it in GitHub Desktop.
Save carlzulauf/1724506 to your computer and use it in GitHub Desktop.
PostgreSQL function for haversine distance calculation, in miles
-- Haversine Formula based geodistance in miles (constant is diameter of Earth in miles)
-- Based on a similar PostgreSQL function found here: https://gist.github.com/831833
-- Updated to use distance formulas found here: http://www.codecodex.com/wiki/Calculate_distance_between_two_points_on_a_globe
CREATE OR REPLACE FUNCTION public.geodistance(alat double precision, alng double precision, blat double precision, blng double precision)
RETURNS double precision AS
$BODY$
SELECT asin(
sqrt(
sin(radians($3-$1)/2)^2 +
sin(radians($4-$2)/2)^2 *
cos(radians($1)) *
cos(radians($3))
)
) * 7926.3352 AS distance;
$BODY$
LANGUAGE sql IMMUTABLE
COST 100;
@ggallo
Copy link

ggallo commented Jan 18, 2018

@FruitAndAShape Late to the party but Haversine requires a final multiplication by 2. 7926 is twice the radius of the earth in miles. You could switch that to 2 * 6371 = 12742 for kilometers.

@florent-pasquer-needone
Copy link

@FruitAndAShape Late to the party but Haversine requires a final multiplication by 2. 7926 is twice the radius of the earth in miles. You could switch that to 2 * 6371 = 12742 for kilometers.

Thanks :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment