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


在本教學課程中,您將使用 Colab 筆記本,以視覺化方式呈現 BigQuery 中的地理空間分析資料。

本教學課程會使用下列 BigQuery 公開資料集

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

您可以使用公開資料集建立下列示意圖:

  • 福特 GoBike Share 資料集的所有共享單車站點散佈圖
  • 舊金山社區資料集中的多邊形
  • choropleth 地圖:按街區顯示共享單車租借站數量
  • 舊金山警察局報告資料集的事件熱力圖

目標

  • 設定驗證機制,並視需要使用 Google 地圖。 Google Cloud
  • 在 BigQuery 中查詢資料,並將結果下載至 Colab。
  • 使用 Python 數據資料學工具執行轉換和分析。
  • 建立圖表,包括散布圖、多邊形、區域平面圖和熱力圖。

費用

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

您可以使用 Pricing Calculator 根據預測用量產生預估費用。 新 Google Cloud 使用者可能符合申請免費試用的資格。

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

事前準備

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. Make sure that billing is enabled for your Google Cloud project.

  4. Enable the BigQuery and Google Maps JavaScript APIs.

    Enable the APIs

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

    Go to project selector

  6. Make sure that billing is enabled for your Google Cloud project.

  7. Enable the BigQuery and Google Maps JavaScript APIs.

    Enable the APIs

  8. 請確認您具備必要權限,才能執行本文所述的任務。
  9. 必要的角色

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

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

    Make sure that you have the following role or roles on the project:

    Check for the roles

    1. In the Google Cloud console, go to the IAM page.

      Go to IAM
    2. Select the project.
    3. In the Principal column, find all rows that identify you or a group that you're included in. To learn which groups you're included in, contact your administrator.

    4. For all rows that specify or include you, check the Role column to see whether the list of roles includes the required roles.

    Grant the roles

    1. In the Google Cloud console, go to the IAM page.

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

    5. 在「請選擇角色」清單中,選取角色。
    6. 如要授予其他角色,請按一下 「Add another role」(新增其他角色),然後新增其他角色。
    7. 按一下 [Save]
    8. 如要進一步瞭解 BigQuery 中的角色,請參閱「預先定義的 IAM 角色」。

建立 Colab 筆記本

本教學課程將建立 Colab 筆記本,以便以視覺化方式呈現地理空間分析資料。您可以在 Colab、Colab Enterprise 或 BigQuery Studio 中開啟預先建構的筆記本版本,方法是點選 GitHub 版教學課程頂端的連結 - Colab 中的 BigQuery 地理空間可視化功能

  1. 開啟 Colab。

    開啟 Colab

  2. 在「Open notebook」對話方塊中,按一下「New notebook」

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

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

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

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

透過 Google Cloud進行驗證

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

  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」單元格

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

  5. 在「Sign in with Google」頁面上,選擇您的帳戶。

  6. 在「登入第三方作者的 Notebook 程式碼」頁面中,按一下「繼續」

  7. 在「Select what third-party authored notebook code can access」(選取第三方作者的 Notebook 程式碼可存取的內容) 頁面上,按一下「Select all」(選取全部),然後點選「Continue」(繼續)

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

選用:使用 Google 地圖進行驗證

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

只有在使用 Maps API 時,才需要執行這個步驟。如果您未透過 Google 地圖平台進行驗證,pydeck 會改用 carto 地圖。

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

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

  3. 按一下「新增機密金鑰」

  4. 在「Name」 中輸入 GMP_API_KEY

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

  6. 關閉「Secrets」面板。

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

  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. 出現提示時,如果同意,請按一下「授予存取權」,讓 Notebook 存取你的金鑰。

  10. 按一下 「Run」單元格

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

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

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

在本節中,您將安裝 pydeckh3 套件。pydeck 在 Python 中提供高規模空間算繪功能,由 deck.gl 提供支援。h3-py 提供 Uber 的 H3 六邊形階層性地理空間索引系統 (Python 版)。

接著,匯入 h3pydeck 程式庫,以及下列 Python 地理空間程式庫:

  • geopandas 可延伸 pandas 使用的資料類型,允許對幾何圖形類型執行空間運算。
  • shapely:用於操控及分析個別平面幾何物件。
  • branca 可產生 HTML 和 JavaScript 色彩圖。
  • geemap.deck:使用 pydeckearthengine-api 進行視覺化。

匯入程式庫後,您可以為 pandas 資料框架在 Colab 中啟用互動式資料表。

安裝 pydeckh3 套件

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

  2. 如要安裝 pydeckh3 套件,請輸入以下程式碼:

    # Install pydeck and h3.
    !pip install pydeck>=0.9 h3>=4.2
  3. 按一下 「Run」單元格

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

匯入 Python 程式庫

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

  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」單元格

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

為 pandas DataFrame 啟用互動式表格

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

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

    # Enable displaying pandas data frames as interactive tables by default.
    from google.colab import data_table
    data_table.enable_dataframe_formatter()
  3. 按一下 「Run」單元格

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

建立共用處理常式

在本節中,您將建立共用例行程序,在基本地圖上算繪圖層。

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

  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」單元格

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

建立散布圖

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

當您需要查看個別點的子集時 (也稱為點檢),散布圖就很實用。

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

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

  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」單元格

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

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

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

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

    # Get a summary of the DataFrame
    gdf_sf_bikestations.info()
  6. 按一下 「Run」單元格

    輸出內容應如下所示:

    <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. 如要插入程式碼儲存格,請按一下 「程式碼」

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

    # Preview the first five rows
    gdf_sf_bikestations.head()
  9. 按一下 「Run」單元格

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

    DataFrame 的前五列。

您必須從自行車共享資料集的 station_geom 欄中,將經緯度提取為 x 和 y 座標,才能算繪點。

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

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

  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」單元格

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

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

  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」單元格

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

    呈現的共享單車站點散佈圖。

以視覺化方式呈現多邊形

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

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

  • 資料點
  • 線條
  • 多邊形
  • 多邊形集合

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

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

在本節中,您將查詢「San Francisco Neighborhoods」資料集中的地理資料,然後以視覺化方式呈現多邊形。

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

  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」單元格

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

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

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

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

    # Get a summary of the DataFrame
    gdf_sanfrancisco_neighborhoods.info()
  6. 按一下 「Run」單元格

    結果應如下所示:

    <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」單元格

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

    DataFrame 的第一列。

    請注意,結果中的資料是多邊形。

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

  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」單元格

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

    舊金山社區資料集的算繪多邊形。

建立 choropleth 地圖

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

在本節中,您將使用多邊形圖層算繪點陣列,並使用結果算繪 choropleth 地圖。這張等高線地圖會將舊金山鄰里資料集與舊金山 Ford GoBike 共享單車資料集的資料彙整,以顯示各鄰里共享單車站的密度。

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

  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」單元格

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

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

  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」單元格

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

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

  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」單元格

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

    舊金山區域的算繪多邊形圖層。

建立熱視圖

當您有已知且具意義的邊界時,就可以使用等高線圖。如果資料沒有已知的實質邊界,您可以使用熱圖圖層呈現連續密度。

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

針對熱圖,建議您在算繪前先將資料量化並匯總。在這個範例中,系統會使用 Carto 的 H3 空間索引將資料量化並匯總。熱圖是使用 deck.gl 架構中的熱圖圖層建立。

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

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

  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」單元格

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

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

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

  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」單元格

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

    <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. 如要插入程式碼儲存格,請按一下 「程式碼」

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

    # Preview the first five rows.
    gdf_incidents_x_cell.head()
  9. 按一下 「Run」單元格

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

    DataFrame 的前五列。

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

  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」單元格

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

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

  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」單元格

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

    算繪的熱視圖。

清除所用資源

如要避免系統向您的 Google Cloud 帳戶收取本教學課程中所用資源的相關費用,請刪除含有該項資源的專案,或者保留專案但刪除個別資源。

刪除專案

控制台

  1. In the Google Cloud console, go to the Manage resources page.

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then click Delete.
  3. In the dialog, type the project ID, and then click Shut down to delete the project.

gcloud

    Delete a Google Cloud project:

    gcloud projects delete PROJECT_ID

刪除 Google Maps API 金鑰和 Notebook

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

  1. 在 Colab 中,按一下「密鑰」

  2. 按一下 GMP_API_KEY 列結尾的 「刪除」

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

後續步驟