Places API 可傳回特定地點的詳細資訊。本頁面說明 Place 類別 (新版) 和 PlacesService (舊版) 所用地點詳細資料之間的差異,並提供一些程式碼片段以供比較。下表列出 Place 類別和 PlacesService 在使用地點詳細資料時的一些主要差異:
| PlacesService(舊版) | Place(新) | 
|---|---|
| getDetails() | fetchFields() | 
| PlaceDetailsRequest | FetchFieldsRequest | 
| 方法需要使用回呼來處理結果物件和 google.maps.places.PlacesServiceStatus回應。 | 使用 Promise,並以非同步方式運作。 | 
| 方法需要進行 PlacesServiceStatus檢查。 | 不需要檢查狀態,可使用標準錯誤處理程序。 瞭解詳情。 | 
| 地點資料欄位的格式為蛇形命名法。 | 地點資料欄位的格式為駝峰式大小寫。 | 
| 僅限一組固定的地點類型和地點資料欄位。 | 提供更多定期更新的地點類型和地點資料欄位。 | 
程式碼比較
本節會比較兩段類似的程式碼,說明地點服務和 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,
  });
}