處理並顯示 Isochrones API 回應

Isochrones API 會以符合 RFC 7946 的標準 GeoJSON 格式傳回幾何圖形。回應一律會在 isochrone.geoJson (gRPC 中為 isochrone.geo_json) 下方包含 MultiPolygon 幾何圖形物件:

  • 座標順序:每個位置都是 WGS 84 十進制度數的 [longitude, latitude] 配對。
  • 多個多邊形 (coordinates[i]):可到達的等時線區域可能由多個不相交的多邊形組成 (例如,高速橋梁或隧道連接到獨立的可到達區域,或跨越 ±180° 對子午線的多邊形,根據 RFC 7946 §3.1.9 沿子午線分割)。
  • 外殼和內部孔洞 (coordinates[i][j]):在每個多邊形 coordinates[i] 中,第一個線性環 (coordinates[i][0]) 是逆時針纏繞的外殼,後續的任何線性環 (coordinates[i][1..k]) 則代表順時針纏繞的內部孔洞 (例如湖泊、公園或未對應的口袋),符合 RFC 7946 §3.1.6 右手規則。每個線性環都是封閉的 (第一個和最後一個 [longitude, latitude] 位置相同)。

以下範例顯示 MultiPolygon 回應,其中包含一個有內洞的主要多邊形,以及第二個不相交的多邊形:

{
  "isochrone": {
    "geoJson": {
      "type": "MultiPolygon",
      "coordinates": [
        [
          [
            [-122.340000, 47.600000],
            [-122.320000, 47.600000],
            [-122.320000, 47.615000],
            [-122.340000, 47.615000],
            [-122.340000, 47.600000]
          ],
          [
            [-122.334000, 47.604000],
            [-122.334000, 47.609000],
            [-122.328000, 47.609000],
            [-122.328000, 47.604000],
            [-122.334000, 47.604000]
          ]
        ],
        [
          [
            [-122.355000, 47.602000],
            [-122.348000, 47.602000],
            [-122.348000, 47.608000],
            [-122.355000, 47.608000],
            [-122.355000, 47.602000]
          ]
        ]
      ]
    }
  }
}

在地圖上以圖表呈現等時線

由於 API 會傳回標準 GeoJSON,您可以使用 Maps JavaScript API 視覺化呈現回應。google.maps.Data 類別原生支援 GeoJSON,因此您不必手動反轉 [longitude, latitude] 座標順序。

下列 JavaScript 程式碼片段示範如何將 API 回應直接加入地圖:

// Assume 'map' is an initialized google.maps.Map object
// and 'responseData' is the parsed JSON payload returned by the Isochrones API.

const isochroneGeoJson = responseData.isochrone.geoJson;

// Wrap the geometry in a standard GeoJSON Feature
const geoJsonFeature = {
    type: "Feature",
    geometry: isochroneGeoJson,
    properties: {}
};

// Add the GeoJSON Feature to the map's data layer
map.data.addGeoJson(geoJsonFeature);

// Optional: Apply custom styling to the isochrone polygon
map.data.setStyle({
    fillColor: '#4285F4',
    fillOpacity: 0.3,
    strokeColor: '#4285F4',
    strokeWeight: 2
});