-
-
Save dux/1e635fa1acf618fb3a325013e35fb5cf to your computer and use it in GitHub Desktop.
PostgreSQL function for haversine distance calculation, in miles
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment