Skip to content

Instantly share code, notes, and snippets.

@nkt
Created February 23, 2015 22:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nkt/cd768ea29d533bbebe4e to your computer and use it in GitHub Desktop.
Save nkt/cd768ea29d533bbebe4e to your computer and use it in GitHub Desktop.
Postgres function for calculating measure in meters between two points
CREATE FUNCTION measure(_from POINT, _to POINT)
RETURNS DOUBLE PRECISION AS $$
DECLARE
d_lat DOUBLE PRECISION;
d_lon DOUBLE PRECISION;
_a DOUBLE PRECISION;
_c DOUBLE PRECISION;
_d DOUBLE PRECISION;
BEGIN
d_lat = (_to [0] - _from [0]) * pi() / 180;
d_lon = (_to [1] - _from [1]) * pi() / 180;
_a = sin(d_lat / 2) * sin(d_lat / 2) +
cos(_from [0] * pi() / 180) * cos(_to [0] * pi() / 180) *
sin(d_lon / 2) * sin(d_lon / 2);
_c = 2 * atan2(sqrt(_a), sqrt(1 - _a));
_d = 6378.137 * _c;
RETURN _d * 1000;
END;
$$ LANGUAGE plpgsql;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment