Skip to content

Commit c1ae430

Browse files
make a big query adapted macro
1 parent a4db0f3 commit c1ae430

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

macros/geo/haversine_distance.sql

+25
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,10 @@ http://daynebatten.com/2015/09/latitude-longitude-distance-sql/
66
The arguments should be float type.
77
#}
88

9+
{% macro degrees_to_radians(degrees) -%}
10+
acos(-1) * {{degrees}} / 180
11+
{%- endmacro %}
12+
913
{% macro haversine_distance(lat1,lon1,lat2,lon2,unit='mi') -%}
1014
{{ return(adapter.dispatch('haversine_distance', packages = dbt_utils._get_utils_namespaces())(lat1,lon1,lat2,lon2,unit)) }}
1115
{% endmacro %}
@@ -23,3 +27,24 @@ The arguments should be float type.
2327
pow((sin(radians(({{lon2}} - {{lon1}}) / 2))), 2))) {{conversion_rate}}
2428

2529
{%- endmacro %}
30+
31+
32+
33+
{% macro bigquery__haversine_distance(lat1,lon1,lat2,lon2,unit) -%}
34+
{% set r_lat1 = dbt_utils.degrees_to_radians(lat1) %}
35+
{% set r_lat2 = dbt_utils.degrees_to_radians(lat2) %}
36+
{% set r_lon1 = dbt_utils.degrees_to_radians(lon1) %}
37+
{% set r_lon2 = dbt_utils.degrees_to_radians(lon2) %}
38+
{# vanilla macro is in miles #}
39+
{% set conversion_rate = '' %}
40+
{% if unit == 'km' %}
41+
{# we multiply miles result to get it in kms #}
42+
{% set conversion_rate = '* 1.60934' %}
43+
{% endif %}
44+
45+
2 * 3961 * asin(sqrt(pow(sin(({{r_lat2}} - {{r_lat1}}) / 2), 2) +
46+
cos({{r_lat1}}) * cos({{r_lat2}}) *
47+
pow(sin(({{r_lon2}} - {{r_lon1}}) / 2), 2))) {{conversion_rate}}
48+
49+
{%- endmacro %}
50+

0 commit comments

Comments
 (0)