Skip to content

Instantly share code, notes, and snippets.

@technetium
Last active March 29, 2019 10:26
Show Gist options
  • Save technetium/d7b2b79d3ee5263929cb3b4708fb878b to your computer and use it in GitHub Desktop.
Save technetium/d7b2b79d3ee5263929cb3b4708fb878b to your computer and use it in GitHub Desktop.
Create a function to calculate the distance between two points on the earth. This function assumes the input to be decimal degrees and the earth to be a sphere with a radius of 6371 km
CREATE FUNCTION distance (lat1 REAL, lng1 REAL, lat2 REAL, lng2 REAL)
RETURNS REAL DETERMINISTIC
RETURN 2 * 6371 * ASIN(SQRT(
SIN(RADIANS(lat1 - lat2)/2) * SIN(RADIANS(lat1 - lat2)/2) +
COS(RADIANS(lat1)) * COS(RADIANS(lat2)) *
SIN(RADIANS(lng1 - lng2)/2) * SIN(RADIANS(lng1 - lng2)/2)
));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment