Skip to content

Instantly share code, notes, and snippets.

@Faks
Created May 1, 2021 08:59
Show Gist options
  • Save Faks/e8966538dc97ae20757684a08be73709 to your computer and use it in GitHub Desktop.
Save Faks/e8966538dc97ae20757684a08be73709 to your computer and use it in GitHub Desktop.
haversine.sql
/**
@ Original Author pimplesushant
@ Credits to: Faks changed to work with meters reference to https://gist.github.com/aramonc/6259563
*/
CREATE FUNCTION haversine(
lat1 REAL,
lng1 REAL,
lat2 REAL,
lng2 REAL
) RETURNS REAL
NO SQL
RETURN ATAN2(
SQRT(
POW(COS(RADIANS(lat2)) * SIN(RADIANS(lng1 - lng2)), 2) +
POW(COS(RADIANS(lat1)) * SIN(RADIANS(lat2)) -
SIN(RADIANS(lat1)) * COS(RADIANS(lat2)) *
COS(RADIANS(lng1 - lng2)), 2)
),
(
SIN(RADIANS(lat1)) * SIN(RADIANS(lat2)) +
COS(RADIANS(lat1)) * COS(RADIANS(lat2)) * COS(RADIANS(lng1 - lng2))
)
) * 6371000;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment