Last active
May 24, 2020 14:51
-
-
Save n0531m/b4b40565f44915e657862cab29ea1d2a to your computer and use it in GitHub Desktop.
UDF to calculate bearing in BigQuery
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
# | |
# https://en.wikipedia.org/wiki/Radian | |
# https://towardsdatascience.com/calculating-the-bearing-between-two-geospatial-coordinates-66203f57e4b4 | |
CREATE TEMP FUNCTION | |
PI (degree float64) AS (ACOS(-1)); | |
CREATE TEMP FUNCTION | |
RADIANS (degree FLOAT64) AS (degree * ACOS(-1) / 180); | |
CREATE TEMP FUNCTION | |
DEGREES (radian FLOAT64) AS (radian * 180 / ACOS(-1)); | |
CREATE TEMP FUNCTION | |
BEARING( | |
src_lat FLOAT64, src_lng FLOAT64, | |
dst_lat FLOAT64, dst_lng FLOAT64 | |
) | |
RETURNS FLOAT64 AS ( | |
DEGREES( | |
ATAN2( | |
SIN(RADIANS(src_lng-dst_lng))*COS(RADIANS(src_lat)), | |
COS(RADIANS(dst_lat))*SIN(RADIANS(src_lat)) -SIN(RADIANS(dst_lat))*COS(RADIANS(src_lat))* COS(RADIANS(src_lng-dst_lng)) | |
) | |
) | |
); | |
CREATE TEMP FUNCTION | |
BEARING_GEO(p1 GEOGRAPHY, p2 GEOGRAPHY) | |
RETURNS FLOAT64 AS ( | |
DEGREES( | |
ATAN2( | |
SIN(RADIANS(ST_X(p1)-ST_X(p2)))*COS(RADIANS(ST_Y(p1))), | |
COS(RADIANS(ST_Y(p2)))*SIN(RADIANS(ST_Y(p1))) -SIN(RADIANS(ST_Y(p2)))*COS(RADIANS(ST_Y(p1)))* COS(RADIANS(ST_X(p1)-ST_X(p2))) | |
) | |
) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment