Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 884
Felipe Hoffa Avatar asked Dec 08 '18 00:12

Felipe Hoffa


People also ask

How do I find LAT LNG address?

There is a last trick to get Address from Lat-Long (Geo-coordinates). You can simply hit google-maps web service passing the Latitude and longitude. It is simply a GET-Method web-service.

What is geocoding and reverse geocoding explain with example?

Geocoding is the process of transforming a street address or other description of a location into a (latitude, longitude) coordinate. Reverse geocoding is the process of transforming a (latitude, longitude) coordinate into a (partial) address.

Is reverse geocoding accurate?

Reverse geocoding results will be imprecise as well. Administrative area geocoding provides the lowest level of geocoding accuracy to connect an area with a location such as a state or province. It is not possible to connect state or provincial level coordinates to a specific address.


1 Answers

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

enter image description here

like image 175
Felipe Hoffa Avatar answered Oct 02 '22 07:10

Felipe Hoffa