Reverse- geocoding: How to determine the city closest to a (lat,lon) with BigQuery SQL?

前端 未结 2 1904
旧时难觅i
旧时难觅i 2020-11-30 14:32

I have a huge collection of points - and I want to determine the closest city to each point. How can I do this with BigQuery?

2条回答
  •  不知归路
    2020-11-30 14:51

    This is the best performing query we've worked out so far:

    WITH a AS (
      # a table with points around the world
      SELECT * FROM UNNEST([ST_GEOGPOINT(-70, -33), ST_GEOGPOINT(-122,37), ST_GEOGPOINT(151,-33)]) my_point
    ), b AS (
      # any table with cities world locations
      SELECT *, ST_GEOGPOINT(lon,lat) latlon_geo
      FROM `fh-bigquery.geocode.201806_geolite2_latlon_redux` 
    )
    
    SELECT my_point, city_name, subdivision_1_name, country_name, continent_name
    FROM (
      SELECT loc.*, my_point
      FROM (
        SELECT ST_ASTEXT(my_point) my_point, ANY_VALUE(my_point) geop
          , ARRAY_AGG( # get the closest city
               STRUCT(city_name, subdivision_1_name, country_name, continent_name) 
               ORDER BY ST_DISTANCE(my_point, b.latlon_geo) LIMIT 1
            )[SAFE_OFFSET(0)] loc
        FROM a, b 
        WHERE ST_DWITHIN(my_point, b.latlon_geo, 100000)  # filter to only close cities
        GROUP BY my_point
      )
    )
    GROUP BY 1,2,3,4,5
    

提交回复
热议问题