使用 Colab 筆記本將地理空間分析資料視覺化

在 Colab 筆記本中以圖表呈現地理空間分析資料,即可使用熟悉的 Python 資料科學工具探索位置資料。在本教學課程中,您將直接從筆記本查詢下列公開資料集,並透過轉譯互動式散布圖、多邊形、choropleth 地圖和熱視圖,找出地理模式:

如要瞭解如何存取這些公開資料集,請參閱「在 Google Cloud 控制台中存取公開資料集」。

目標

  • 使用 Google Cloud 和 Google 地圖 (選用) 設定驗證。
  • 在 BigQuery 中查詢資料,並將結果下載至 Colab。
  • 使用 Python 資料科學工具執行轉換和分析。
  • 建立視覺化圖表,包括散布圖、多邊形、等值區域圖和熱視圖。

費用

在本文件中,您會使用下列 Google Cloud計費元件:

您可以使用 Pricing Calculator,根據預測用量估算費用。

初次使用 Google Cloud 的使用者可能符合免費試用期資格。

完成本文所述工作後,您可以刪除建立的資源,避免繼續計費,詳情請參閱「清除所用資源」。

事前準備

  1. 登入 Google Cloud 帳戶。如果您未曾使用過 Google Cloud,歡迎 建立帳戶,親自體驗實際使用我們產品的成效。新客戶還能獲得價值 $300 美元的免費抵免額,用於執行、測試及部署工作負載。
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the BigQuery and Google Maps JavaScript APIs, if any are not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the APIs

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  6. Verify that billing is enabled for your Google Cloud project.

  7. Enable the BigQuery and Google Maps JavaScript APIs, if any are not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the APIs

  8. 確認您具備必要權限,可執行本文件中的工作。

必要的角色

如果您建立新專案,您就是專案擁有者,並會獲得完成本教學課程所需的所有必要 IAM 權限。

如果使用現有專案,您需要下列專案層級角色,才能執行查詢工作。

確認您具備下列專案角色:

檢查角色

  1. 前往 Google Cloud 控制台的「IAM」頁面。

    前往「IAM」頁面
  2. 選取專案。
  3. 在「Principal」(主體) 欄中,找出所有代表您或您所屬群組的資料列。如要瞭解您所屬的群組,請與管理員聯絡。

  4. 在指定或包含您的所有資料列中,查看「Role」(角色) 欄,確認角色清單是否包含必要角色。

授予角色

  1. 前往 Google Cloud 控制台的「IAM」頁面。

    前往「IAM」頁面
  2. 選取專案。
  3. 按一下「Grant access」(授予存取權)。
  4. 在「New principals」(新增主體) 欄位中,輸入您的使用者 ID。 這通常是指 Google 帳戶的電子郵件地址。

  5. 按一下「Select a role」(選取角色),然後搜尋角色。
  6. 如要授予其他角色,請按一下「Add another role」(新增其他角色),然後新增其他角色。
  7. 按一下「Save」(儲存)。

如要進一步瞭解 BigQuery 中的角色,請參閱「預先定義的身分與存取權管理角色」。

建立 Colab 筆記本

本教學課程會建立 Colab 筆記本,以視覺化方式呈現地理空間分析資料。如要開啟預先建構版本的筆記本,請前往 GitHub 版本的教學課程「BigQuery Geospatial Visualization in Colab」,然後點選頂端的連結,即可在 Colab、Colab Enterprise 或 BigQuery Studio 中開啟。

  1. 開啟 Colab。

    開啟 Colab

  2. 在「開啟筆記本」對話方塊中,點選「新增筆記本」。

  3. 按一下 Untitled0.ipynb,將筆記本名稱變更為 bigquery-geo.ipynb。

  4. 依序選取「檔案」 > 「儲存」。

使用 Google Cloud 和 Google 地圖進行驗證

本教學課程會查詢 BigQuery 資料集,並使用 Google Maps JavaScript API。如要使用這些資源,請使用 Google Cloud 和 Maps API 驗證 Colab 執行階段。

使用 Google Cloud進行驗證

  1. 如要插入程式碼儲存格,請按一下 「Code」(程式碼)。

  2. 如要驗證專案,請輸入下列程式碼:

    # REQUIRED: Authenticate with your project.
    GCP_PROJECT_ID = "PROJECT_ID"  #@param {type:"string"}
    
    from google.colab import auth
    from google.colab import userdata
    
    auth.authenticate_user(project_id=GCP_PROJECT_ID)
    
    # Set GMP_API_KEY to none
    GMP_API_KEY = None

    將 PROJECT_ID 替換為專案 ID。

  3. 按一下「 Run cell」(執行儲存格)。

  4. 出現提示時,如果您同意,請按一下「Allow」(允許),允許 Colab 存取您的憑證。

  5. 在「使用 Google 帳戶登入」頁面中,選擇您的帳戶。

  6. 在「Sign in to Third-party authored notebook code」(登入第三方編寫的筆記本程式碼) 頁面,按一下「Continue」(繼續)。

  7. 在「Select what third-party authored notebook code can access」部分,依序點選「Select all」和「Continue」。

    完成授權流程後,Colab 筆記本不會產生任何輸出內容。儲存格旁的勾號表示程式碼已成功執行。

選用:透過 Google 地圖進行驗證

如果您使用 Google Maps Platform 做為基本地圖的地圖供應商,則必須提供 Google Maps Platform API 金鑰。筆記本會從 Colab 機密擷取金鑰。

只有在使用 Maps API 時,才需要執行這個步驟。如未向 Google Maps Platform 驗證,pydeck 會改用 carto 地圖。

  1. 請按照 Google 地圖說明文件「使用 API 金鑰」頁面的操作說明,取得 Google Maps API 金鑰。

  2. 切換至 Colab 筆記本,然後按一下 「Secrets」。

  3. 按一下「新增密鑰」。

  4. 在「Name」(名稱) 中輸入 GMP_API_KEY。

  5. 在「Value」部分,輸入先前產生的 Maps API 金鑰值。

  6. 關閉「Secrets」面板。

  7. 如要插入程式碼儲存格,請按一下 「Code」(程式碼)。

  8. 如要使用 Maps API 進行驗證,請輸入下列程式碼:

    # Authenticate with the Google Maps JavaScript API.
    GMP_API_SECRET_KEY_NAME = "GMP_API_KEY" #@param {type:"string"}
    
    if GMP_API_SECRET_KEY_NAME:
      GMP_API_KEY = userdata.get(GMP_API_SECRET_KEY_NAME) if GMP_API_SECRET_KEY_NAME else None
    else:
      GMP_API_KEY = None
  9. 如果同意,請在系統提示時點選「Grant access」(授予存取權),授予筆記本金鑰存取權。

  10. 按一下「 Run cell」(執行儲存格)。

    完成授權流程後,Colab 筆記本不會產生任何輸出內容。儲存格旁的勾號表示程式碼已成功執行。

安裝 Python 套件並匯入資料科學程式庫

除了 colabtools (google.colab) Python 模組外,本教學課程還會使用其他幾個 Python 套件和資料科學程式庫。

在本節中,您將安裝 pydeck 和 h3 套件。pydeck 採用 deck.gl 技術,可在 Python 中提供大規模空間算繪功能。 h3-py 提供 Uber 的 H3 六角形階層式地理空間索引系統 (Python)。

接著,您會匯入 h3 和 pydeck 程式庫,以及下列 Python 地理空間程式庫:

  • geopandas:擴充 pandas 使用的資料類型,允許對幾何類型執行空間運算。
  • shapely:用於操作及分析個別平面幾何物件。
  • branca:產生 HTML 和 JavaScript 色彩對應。
  • geemap.deck 使用 pydeck 和 earthengine-api 建立圖表。

匯入程式庫後,您會在 Colab 中為 pandas DataFrame 啟用互動式表格。

安裝 pydeck 和 h3 套件

  1. 如要插入程式碼儲存格,請按一下 「Code」(程式碼)。

  2. 如要安裝 pydeck 和 h3 套件,請輸入下列程式碼:

    # Install pydeck and h3.
    !pip install pydeck>=0.9 h3>=4.2
  3. 按一下「 Run cell」(執行儲存格)。

    安裝完成後,Colab 筆記本不會產生任何輸出內容。儲存格旁的勾號表示程式碼已成功執行。

匯入 Python 程式庫

  1. 如要插入程式碼儲存格,請按一下 「Code」(程式碼)。

  2. 如要匯入 Python 程式庫,請輸入下列程式碼:

    # Import data science libraries.
    import branca
    import geemap.deck as gmdk
    import h3
    import pydeck as pdk
    import geopandas as gpd
    import shapely
  3. 按一下「 Run cell」(執行儲存格)。

    執行程式碼後,Colab 筆記本不會產生任何輸出內容。儲存格旁的勾號表示程式碼已成功執行。

為 pandas DataFrame 啟用互動式表格

  1. 如要插入程式碼儲存格,請按一下 「Code」(程式碼)。

  2. 如要啟用 pandas DataFrames,請輸入下列程式碼:

    # Enable displaying pandas data frames as interactive tables by default.
    from google.colab import data_table
    data_table.enable_dataframe_formatter()
  3. 按一下「 Run cell」(執行儲存格)。

    執行程式碼後,Colab 筆記本不會產生任何輸出內容。儲存格旁的勾號表示程式碼已成功執行。

建立共用日常安排

在本節中,您將建立共用常式,在基本地圖上算繪圖層。

  1. 如要插入程式碼儲存格,請按一下 「Code」(程式碼)。

  2. 如要建立共用常式,在地圖上算繪圖層,請輸入下列程式碼:

    # Set Google Maps as the base map provider.
    MAP_PROVIDER_GOOGLE = pdk.bindings.base_map_provider.BaseMapProvider.GOOGLE_MAPS.value
    
    # Shared routine for rendering layers on a map using geemap.deck.
    def display_pydeck_map(layers, view_state, **kwargs):
      deck_kwargs = kwargs.copy()
    
      # Use Google Maps as the base map only if the API key is provided.
      if GMP_API_KEY:
        deck_kwargs.update({
          "map_provider": MAP_PROVIDER_GOOGLE,
          "map_style": pdk.bindings.map_styles.GOOGLE_ROAD,
          "api_keys": {MAP_PROVIDER_GOOGLE: GMP_API_KEY},
        })
    
      m = gmdk.Map(initial_view_state=view_state, ee_initialize=False, **deck_kwargs)
    
      for layer in layers:
        m.add_layer(layer)
      return m
  3. 按一下「 Run cell」(執行儲存格)。

    執行程式碼後,Colab 筆記本不會產生任何輸出內容。儲存格旁的勾號表示程式碼已成功執行。

建立散布圖

在本節中,您將從 bigquery-public-data.san_francisco_bikeshare.bikeshare_station_info 資料表擷取資料,為舊金山 Ford GoBike Share 公開資料集中的所有共享單車站點建立散布圖。散布圖是使用 deck.gl 架構中的圖層和散布圖圖層建立。

如需查看個別資料點的子集 (也稱為「抽查」),散布圖就非常實用。

以下範例說明如何使用圖層和散布圖圖層,將個別點算繪為圓形。

  1. 如要插入程式碼儲存格,請按一下 「Code」(程式碼)。

  2. 如要查詢舊金山 Ford GoBike Share 公開資料集,請輸入下列程式碼。這段程式碼會使用 %%bigquery 魔術函式執行查詢,並在 DataFrame 中傳回結果:

    # Query the station ID, station name, station short name, and station
    # geometry from the bike share dataset.
    # NOTE: In this tutorial, the denormalized 'lat' and 'lon' columns are
    # ignored. They are decomposed components of the geometry.
    %%bigquery gdf_sf_bikestations --project {GCP_PROJECT_ID} --use_geodataframe station_geom
    
    SELECT
      station_id,
      name,
      short_name,
      station_geom
    FROM
      `bigquery-public-data.san_francisco_bikeshare.bikeshare_station_info`
  3. 按一下「 Run cell」(執行儲存格)。

    輸出結果會與下列內容相似:

    Job ID 12345-1234-5678-1234-123456789 successfully executed: 100%

  4. 如要插入程式碼儲存格,請按一下 「Code」(程式碼)。

  5. 如要取得 DataFrame 的摘要 (包括資料欄和資料類型),請輸入下列程式碼:

    # Get a summary of the DataFrame
    gdf_sf_bikestations.info()
  6. 按一下「 Run cell」(執行儲存格)。

    輸出內容應如下所示:

    <class 'geopandas.geodataframe.GeoDataFrame'>
    RangeIndex: 472 entries, 0 to 471
    Data columns (total 4 columns):
    #   Column        Non-Null Count  Dtype
    ---  ------        --------------  -----
    0   station_id    472 non-null    object
    1   name          472 non-null    object
    2   short_name    472 non-null    object
    3   station_geom  472 non-null    geometry
    dtypes: geometry(1), object(3)
    memory usage: 14.9+ KB
    
  7. 如要插入程式碼儲存格,請按一下 「Code」(程式碼)。

  8. 如要預覽 DataFrame 的前五列,請輸入下列程式碼:

    # Preview the first five rows
    gdf_sf_bikestations.head()
  9. 按一下「 Run cell」(執行儲存格)。

    輸出結果會與下列內容相似:

    DataFrame 的前五列。

如要算繪點,您必須從共享單車資料集的 station_geom 欄中,擷取經度和緯度做為 x 和 y 座標。

由於 gdf_sf_bikestations 是 geopandas.GeoDataFrame,因此可直接從其 station_geom 幾何圖形欄存取座標。您可以使用資料欄的 .x 屬性擷取經度,並使用 .y 屬性擷取緯度。然後將這些值儲存在新的經度和緯度欄中。

  1. 如要插入程式碼儲存格,請按一下 「Code」(程式碼)。

  2. 如要從 station_geom 欄擷取經緯度值,請輸入下列程式碼:

    # Extract the longitude (x) and latitude (y) from station_geom.
    gdf_sf_bikestations["longitude"] = gdf_sf_bikestations["station_geom"].x
    gdf_sf_bikestations["latitude"] = gdf_sf_bikestations["station_geom"].y
  3. 按一下「 Run cell」(執行儲存格)。

    執行程式碼後,Colab 筆記本不會產生任何輸出內容。儲存格旁的勾號表示程式碼已成功執行。

  4. 如要插入程式碼儲存格,請按一下 「Code」(程式碼)。

  5. 如要根據先前擷取的經緯度值,轉譯共享單車站點的散布圖,請輸入下列程式碼:

    # Render a scatter plot using pydeck with the extracted longitude and
    # latitude columns in the gdf_sf_bikestations geopandas.GeoDataFrame.
    scatterplot_layer = pdk.Layer(
      "ScatterplotLayer",
      id="bike_stations_scatterplot",
      data=gdf_sf_bikestations,
      get_position=['longitude', 'latitude'],
      get_radius=100,
      get_fill_color=[255, 0, 0, 140],  # Adjust color as desired
      pickable=True,
    )
    
    view_state = pdk.ViewState(latitude=37.77613, longitude=-122.42284, zoom=12)
    display_pydeck_map([scatterplot_layer], view_state)
  6. 按一下「 Run cell」(執行儲存格)。

    輸出結果會與下列內容相似:

    共享單車站點的散布圖算繪結果。

以圖表呈現多邊形

地理空間分析功能可讓您使用 GEOGRAPHY 資料類型和 GoogleSQL 地理函式,在 BigQuery 中分析地理空間資料,並以圖表呈現。

地理空間分析中的 GEOGRAPHY 資料類型是點、線串和多邊形的集合,以點集或地球表面的子集表示。GEOGRAPHY 類型可包含下列物件:

  • 資料點
  • 線條
  • 多邊形
  • 多重多邊形

如需所有支援物件的清單,請參閱 GEOGRAPHY 類型說明文件。

如果取得地理空間資料,但不知道預期的形狀,可以將資料視覺化,找出形狀。您可以將地理資料轉換為 GeoJSON 格式,以視覺化方式呈現形狀。接著,您可以使用 deck.gl 架構中的 GeoJSON 圖層,以視覺化方式呈現 GeoJSON 資料。

在本節中,您將查詢 San Francisco Neighborhoods 資料集中的地理資料,然後以多邊形呈現。

  1. 如要插入程式碼儲存格,請按一下 「Code」(程式碼)。

  2. 如要查詢舊金山鄰近地區資料集中 bigquery-public-data.san_francisco_neighborhoods.boundaries 資料表的地理資料,請輸入下列程式碼。這段程式碼會使用 %%bigquery 魔術函式執行查詢,並在 DataFrame 中傳回結果:

    # Query the neighborhood name and geometry from the San Francisco
    # neighborhoods dataset.
    %%bigquery gdf_sanfrancisco_neighborhoods --project {GCP_PROJECT_ID} --use_geodataframe geometry
    
    SELECT
      neighborhood,
      neighborhood_geom AS geometry
    FROM
      `bigquery-public-data.san_francisco_neighborhoods.boundaries`
  3. 按一下「 Run cell」(執行儲存格)。

    輸出結果會與下列內容相似:

    Job ID 12345-1234-5678-1234-123456789 successfully executed: 100%

  4. 如要插入程式碼儲存格,請按一下 「Code」(程式碼)。

  5. 如要取得 DataFrame 的摘要,請輸入下列程式碼:

    # Get a summary of the DataFrame
    gdf_sanfrancisco_neighborhoods.info()
  6. 按一下「 Run cell」(執行儲存格)。

    結果應如下所示:

    <class 'geopandas.geodataframe.GeoDataFrame'>
    RangeIndex: 117 entries, 0 to 116
    Data columns (total 2 columns):
    #   Column        Non-Null Count  Dtype
    ---  ------        --------------  -----
    0   neighborhood  117 non-null    object
    1   geometry      117 non-null    geometry
    dtypes: geometry(1), object(1)
    memory usage: 2.0+ KB
    
  7. 如要預覽 DataFrame 的第一列,請輸入下列程式碼:

    # Preview the first row
    gdf_sanfrancisco_neighborhoods.head(1)
  8. 按一下「 Run cell」(執行儲存格)。

    輸出結果會與下列內容相似:

    DataFrame 的第一列。

    在結果中,您會發現資料是多邊形。

  9. 如要插入程式碼儲存格,請按一下 「Code」(程式碼)。

  10. 如要以視覺化方式呈現多邊形,請輸入下列程式碼。pydeck 用於將幾何圖形欄中的每個 shapely 物件例項轉換為 GeoJSON 格式:

    # Visualize the polygons.
    geojson_layer = pdk.Layer(
        'GeoJsonLayer',
        id="sf_neighborhoods",
        data=gdf_sanfrancisco_neighborhoods,
        get_line_color=[127, 0, 127, 255],
        get_fill_color=[60, 60, 60, 50],
        get_line_width=100,
        pickable=True,
        stroked=True,
        filled=True,
      )
    view_state = pdk.ViewState(latitude=37.77613, longitude=-122.42284, zoom=12)
    display_pydeck_map([geojson_layer], view_state)
  11. 按一下「 Run cell」(執行儲存格)。

    輸出結果會與下列內容相似:

    舊金山鄰近地區資料集算繪的多邊形。

建立 choropleth 地圖

如果探索資料時,多邊形難以轉換為 GeoJSON 格式,可以改用 deck.gl 架構中的多邊形圖層。多邊形圖層可處理特定類型的輸入資料,例如點陣列。

在本節中,您將使用多邊形圖層算繪點陣列,並使用結果算繪 choropleth 地圖。choropleth 地圖會彙整「舊金山鄰近地區」資料集和「舊金山 Ford GoBike 共享單車」資料集的資料,顯示各鄰近地區的共享單車站密度。

  1. 如要插入程式碼儲存格,請按一下 「Code」(程式碼)。

  2. 如要匯總並計算每個鄰里的車站數量,並建立包含點陣列的 polygon 欄,請輸入下列程式碼:

    # Aggregate and count the number of stations per neighborhood.
    gdf_count_stations = gdf_sanfrancisco_neighborhoods.sjoin(gdf_sf_bikestations, how='left', predicate='contains')
    gdf_count_stations = gdf_count_stations.groupby(by='neighborhood')['station_id'].count().rename('num_stations')
    gdf_stations_x_neighborhood = gdf_sanfrancisco_neighborhoods.join(gdf_count_stations, on='neighborhood', how='inner')
    
    # To simulate non-GeoJSON input data, create a polygon column that contains
    # an array of points by using the pandas.Series.map method.
    gdf_stations_x_neighborhood['polygon'] = gdf_stations_x_neighborhood['geometry'].map(lambda g: list(g.exterior.coords))
  3. 按一下 「Run cell」(執行儲存格)。

    執行程式碼後,Colab 筆記本不會產生任何輸出內容。儲存格旁的勾號表示程式碼已成功執行。

  4. 如要插入程式碼儲存格,請按一下 「Code」(程式碼)。

  5. 如要為每個多邊形新增 fill_color 欄,請輸入下列程式碼:

    # Create a color map gradient using the branch library, and add a fill_color
    # column for each of the polygons.
    colormap = branca.colormap.LinearColormap(
      colors=["lightblue", "darkred"],
      vmin=0,
      vmax=gdf_stations_x_neighborhood['num_stations'].max(),
    )
    gdf_stations_x_neighborhood['fill_color'] = gdf_stations_x_neighborhood['num_stations'] \
      .map(lambda c: list(colormap.rgba_bytes_tuple(c)[:3]) + [0.7 * 255])   # force opacity of 0.7
  6. 按一下「 Run cell」(執行儲存格)。

    執行程式碼後,Colab 筆記本不會產生任何輸出內容。儲存格旁的勾號表示程式碼已成功執行。

  7. 如要插入程式碼儲存格,請按一下 「Code」(程式碼)。

  8. 如要算繪多邊形圖層,請輸入下列程式碼:

    # Render the polygon layer.
    polygon_layer = pdk.Layer(
      'PolygonLayer',
      id="bike_stations_choropleth",
      data=gdf_stations_x_neighborhood,
      get_polygon='polygon',
      get_fill_color='fill_color',
      get_line_color=[0, 0, 0, 255],
      get_line_width=50,
      pickable=True,
      stroked=True,
      filled=True,
    )
    view_state = pdk.ViewState(latitude=37.77613, longitude=-122.42284, zoom=12)
    display_pydeck_map([polygon_layer], view_state)
  9. 按一下 「Run cell」(執行儲存格)。

    輸出結果會與下列內容相似:

    舊金山鄰近地區的算繪多邊形圖層。

建立熱視圖

如果已知有意義的界線,就適合使用等值區域圖。如果資料沒有明確的界線,可以使用熱視圖層呈現連續密度。

在以下範例中,您將查詢舊金山警察局 (SFPD) 報告資料集中 bigquery-public-data.san_francisco_sfpd_incidents.sfpd_incidents 資料表的資料。這些資料用於以視覺化方式呈現 2015 年的事件分布情形。

如果是熱視圖,建議您先量化及匯總資料,再進行算繪。在這個範例中,資料會使用 Carto H3 空間索引進行量化和匯總。熱視圖是使用 deck.gl 架構中的熱視圖圖層建立。

在本範例中,量化作業是使用 h3 Python 程式庫完成,將事件點匯總成六邊形。h3.latlng_to_cell 函式用於將事件位置 (經緯度) 對應至 H3 儲存格索引。解析度為 9 的 H3 可為熱視圖提供足夠的匯總六邊形。h3.cell_to_latlng 函式用於判斷每個六邊形的中心。

  1. 如要插入程式碼儲存格,請按一下 「Code」(程式碼)。

  2. 如要查詢舊金山警察局 (SFPD) 報告資料集中的資料,請輸入下列程式碼。這段程式碼會使用 %%bigquery 魔術函式執行查詢,並在 DataFrame 中傳回結果:

    # Query the incident key and location  data from the SFPD reports dataset.
    %%bigquery gdf_incidents --project {GCP_PROJECT_ID} --use_geodataframe location_geography
    
    SELECT
      unique_key,
      location_geography
    FROM (
      SELECT
        unique_key,
        SAFE.ST_GEOGFROMTEXT(location) AS location_geography, # WKT string to GEOMETRY
        EXTRACT(YEAR FROM timestamp) AS year,
      FROM `bigquery-public-data.san_francisco_sfpd_incidents.sfpd_incidents` incidents
    )
    WHERE year = 2015
  3. 按一下「 Run cell」(執行儲存格)。

    輸出結果會與下列內容相似:

    Job ID 12345-1234-5678-1234-123456789 successfully executed: 100%

  4. 如要插入程式碼儲存格,請按一下 「Code」(程式碼)。

  5. 如要計算每個事件經緯度的儲存格、匯總每個儲存格的事件、建構 geopandas DataFrame,以及新增熱視圖圖層的每個六邊形中心,請輸入下列程式碼:

    # Compute the cell for each incident's latitude and longitude.
    H3_RESOLUTION = 9
    gdf_incidents['h3_cell'] = gdf_incidents.geometry.apply(
        lambda geom: h3.latlng_to_cell(geom.y, geom.x, H3_RESOLUTION)
    )
    
    # Aggregate the incidents for each hexagon cell.
    count_incidents = gdf_incidents.groupby(by='h3_cell')['unique_key'].count().rename('num_incidents')
    
    # Construct a new geopandas.GeoDataFrame with the aggregate results.
    # Add the center of each hexagon for the HeatmapLayer to render.
    gdf_incidents_x_cell = gpd.GeoDataFrame(data=count_incidents).reset_index()
    gdf_incidents_x_cell['h3_center'] = gdf_incidents_x_cell['h3_cell'].apply(h3.cell_to_latlng)
    gdf_incidents_x_cell.info()
  6. 按一下 「Run cell」(執行儲存格)。

    輸出結果會與下列內容相似:

    <class 'geopandas.geodataframe.GeoDataFrame'>
    RangeIndex: 969 entries, 0 to 968
    Data columns (total 3 columns):
    #   Column         Non-Null Count  Dtype
    --  ------         --------------  -----
    0   h3_cell        969 non-null    object
    1   num_incidents  969 non-null    Int64
    2   h3_center      969 non-null    object
    dtypes: Int64(1), object(2)
    memory usage: 23.8+ KB
    
  7. 如要插入程式碼儲存格,請按一下 「Code」(程式碼)。

  8. 如要預覽 DataFrame 的前五列,請輸入下列程式碼:

    # Preview the first five rows.
    gdf_incidents_x_cell.head()
  9. 按一下「 Run cell」(執行儲存格)。

    輸出結果會與下列內容相似:

    DataFrame 的前五列。

  10. 如要插入程式碼儲存格,請按一下 「Code」(程式碼)。

  11. 如要將資料轉換為 HeatmapLayer 可使用的 JSON 格式,請輸入下列程式碼:

    # Convert to a JSON format recognized by the HeatmapLayer.
    def _make_heatmap_datum(row) -> dict:
      return {
          "latitude": row['h3_center'][0],
          "longitude": row['h3_center'][1],
          "weight": float(row['num_incidents']),
      }
    
    heatmap_data = gdf_incidents_x_cell.apply(_make_heatmap_datum, axis='columns').values.tolist()
  12. 按一下「 Run cell」(執行儲存格)。

    執行程式碼後,Colab 筆記本不會產生任何輸出內容。儲存格旁的勾號表示程式碼已成功執行。

  13. 如要插入程式碼儲存格,請按一下 「Code」(程式碼)。

  14. 如要算繪熱視圖,請輸入下列程式碼:

    # Render the heatmap.
    heatmap_layer = pdk.Layer(
      "HeatmapLayer",
      id="sfpd_heatmap",
      data=heatmap_data,
      get_position=['longitude', 'latitude'],
      get_weight='weight',
      opacity=0.7,
      radius_pixels=99,  # this limitation can introduce artifacts (see above)
      aggregation='MEAN',
    )
    view_state = pdk.ViewState(latitude=37.77613, longitude=-122.42284, zoom=12)
    display_pydeck_map([heatmap_layer], view_state)
  15. 按一下「 Run cell」(執行儲存格)。

    輸出結果會與下列內容相似:

    算繪後的熱視圖。

清除所用資源

為避免因為本教學課程所用資源,導致系統向 Google Cloud 收取費用,請刪除含有相關資源的專案,或者保留專案但刪除個別資源。

刪除專案

控制台

  1. 前往 Google Cloud 控制台的「Manage resources」(管理資源) 頁面。

    前往「Manage resources」(管理資源)

  2. 在專案清單中選取要刪除的專案,然後點選「Delete」(刪除)。
  3. 在對話方塊中輸入專案 ID,然後按一下 [Shut down] (關閉) 以刪除專案。

gcloud

    刪除 Google Cloud 專案:

    gcloud projects delete PROJECT_ID

刪除 Google Maps API 金鑰和筆記本

刪除 Google Cloud 專案後,如果您使用了 Google Maps API,請從 Colab 密鑰中刪除 Google Maps API 金鑰,然後視需要刪除筆記本。

  1. 在 Colab 中,按一下 「Secrets」。

  2. 在 GMP_API_KEY 資料列末端,按一下 「Delete」(刪除)。

  3. 選用:如要刪除筆記本,請依序點選「File」>「Move to trash」。

後續步驟