Created
February 23, 2015 22:09
-
-
Save nkt/cd768ea29d533bbebe4e to your computer and use it in GitHub Desktop.
Postgres function for calculating measure in meters between two points
This file contains hidden or 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
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