遷移至新的地點詳細資料

歐洲經濟區 (EEA) 開發人員

Places API 可以傳回有關特定地點的詳細資訊。本頁面說明 Place 類別 (新版) 和 PlacesService (舊版) 所用地點詳細資料的差異,並提供一些程式碼片段以供比較。下表列出了Place類別和PlacesService類別在地點詳細資訊使用上的一些主要差異:

PlacesService (舊版) Place (新)
getDetails() fetchFields()
PlaceDetailsRequest FetchFieldsRequest
方法需要使用回呼來處理結果物件和 google.maps.places.PlacesServiceStatus 回應。 使用 Promise,並以非同步方式運作。
方法需要進行 PlacesServiceStatus 檢查。 不需要檢查狀態,可使用標準錯誤處理程序。 瞭解詳情
地點資料欄位的格式為蛇形命名法。 地點資料欄位的格式為駝峰式大小寫。
僅限一組固定的地點類型地點資料欄位 提供更多定期更新的地點類型地點資料欄位

程式碼比較

本節將比較兩段類似的程式碼,以說明 Places 服務和 Place 類別之間的差異。程式碼片段顯示了在每個相應的 API 上發出地點詳細資訊請求所需的程式碼,然後使用生成的地點資料向地圖添加標記。

地點介面集服務 (舊版)

以下精簡的程式碼片段展示如何使用 PlacesService 發出地點詳細資訊請求。此請求使用回調,並包含對 PlacesServiceStatus 的必要條件檢查。請求正文中指定了所需的地點資料欄位。

function getPlaceDetails() {
  // Instantiate the Places Service.
  const service = new google.maps.places.PlacesService(map);

  // Make a request using the Place ID.
  const request = {
    placeId: "ChIJN1t_tDeuEmsRUsoyG83frY4",
    fields: ["name", "formatted_address", "place_id", "geometry"],
  };

  // Request place details.
  service.getDetails(request, (place, status) => {
    // Check whether PlacesServiceStatus is OK.
    if (
      status === google.maps.places.PlacesServiceStatus.OK &&
      place &&
      place.geometry &&
      place.geometry.location
    ) {

      // Log the result.
      console.log(place.name);
      console.log(place.formatted_address);

      // Add a marker for the place.
      const marker = new google.maps.Marker({
        map,
        position: place.geometry.location,
        title: place.name,
      });
    }
  });
}

瞭解詳情

地點類別 (新)

下列簡短的程式碼片段顯示如何使用 Place 類別提出地點詳細資料要求。要求為非同步,且不含狀態檢查 (可使用標準錯誤處理)。地點 ID 用於建立新的 Place 執行個體,該執行個體則用於提出要求 (fetchFields())。在呼叫 fetchFields() 之前,不會傳遞所需的地點資料欄位,因此更具彈性。由於 fetchFields() 方法使用 await 運算子,因此只能在 async 函式內使用。

async function getPlaceDetails() {
  // Use place ID to create a new Place instance.
  const place = new google.maps.places.Place({
    id: "ChIJN5Nz71W3j4ARhx5bwpTQEGg",
    requestedLanguage: "en", // optional
  });

  // Call fetchFields, passing the needed data fields.
  await place.fetchFields({
    fields: ["displayName", "formattedAddress", "location"],
  });

  // Log the result.
  console.log(place.displayName);
  console.log(place.formattedAddress);

  // Add an Advanced Marker.
  const marker = new google.maps.marker.AdvancedMarkerElement({
    map,
    position: place.location,
    title: place.displayName,
  });
}

瞭解詳情