遷移至新的「放置相片」

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

「地點相片」功能可讓您在網頁中加入高品質的相片內容。本頁說明 Place 類別 (新版) 和 PlacesService (舊版) 的地點相片功能差異,並提供一些程式碼片段供您比較。

  • 如果要求中指定了 photos 欄位,PlacesService (舊版) 會在 getDetails() 要求的 PlaceResult 物件中,傳回最多 10 個 PlacePhoto 物件的陣列。如果是 textSearch() 和 nearbySearch(),系統預設會傳回第一張地點相片 (如有)。
  • 如果在 fetchFields() 要求中指定 photos 欄位,Place 類別會傳回最多 10 個 Photo 物件的陣列。

下表列出 Place 類別和 PlacesService 在使用地點相片時的一些主要差異:

PlacesService (舊版) Place (新)
PlacePhoto 介面 Photo 類別
PlacePhoto 會以字串形式傳回 html_attributions。 Photo 會傳回 AuthorAttribution 例項。
方法必須使用回呼,才能處理結果物件和 google.maps.places.PlacesServiceStatus 回應。 使用 Promise,並以非同步方式運作。
方法需要 PlacesServiceStatus 檢查。 不需檢查狀態,可使用標準錯誤處理。 瞭解詳情。
PlacesService 必須使用地圖或 div 元素例項化。 Place 可以在任何需要的地方例項化,不需參照地圖或網頁元素。

程式碼比較

本節會比較地點相片的程式碼,說明 Places 服務和 Place 類別之間的差異。程式碼片段顯示在各個 API 要求地點相片所需的程式碼。

Places 服務 (舊版)

下列程式碼片段顯示如何使用 PlacesService 傳回相片,並在頁面上顯示第一個相片結果。在本例中,Place Details 要求指定了地點 ID,以及 name 和 photos 欄位。檢查服務狀態後,頁面會顯示第一張相片。將 PlacesService 例項化時,必須指定地圖或 div 元素;由於這個範例不含地圖,因此會使用 div 元素。

function getPhotos() {
  // Construct the Place Details request.
  const request = {
    placeId: "ChIJydSuSkkUkFQRsqhB-cEtYnw",
    fields: ["name", "photos"],
  };

  // Create an instance of PlacesService.
  const attributionDiv = document.getElementById("attribution-div");
  const service = new google.maps.places.PlacesService(attributionDiv);

  // Check status and display the first photo in an img element.
  service.getDetails(request, (place, status) => {
    if (
      status === google.maps.places.PlacesServiceStatus.OK && place
    ) {
      const photoImg = document.getElementById('image-container');
      photoImg.src = place.photos[0].getUrl({maxHeight: 400});
    }
  });
}

PlacesService中的作者資訊

PlacesService 會以 html_attributions 字串形式傳回必要的作者姓名標示,其中包含指向作者 Google 個人資料頁面的網址。下列程式碼片段顯示如何擷取第一張相片結果的出處資料。

let attributionUrl = place.photos[0].html_attributions;

瞭解詳情

地點類別 (新)

下列程式碼片段顯示如何使用 fetchFields() 方法,傳回地點詳細資料,包括顯示名稱和地點相片。首先,使用地點 ID 例項化新的 Place 物件,然後呼叫 fetchFields(),並指定 displayName 和 photos 欄位。接著,頁面上會顯示第一張地點相片。使用 Place 類別時,系統會自動處理,因此您不需要檢查服務狀態。

async function getPhotos() {
  // Use a place ID to create a new Place instance.
  const place = new google.maps.places.Place({
      id: 'ChIJydSuSkkUkFQRsqhB-cEtYnw', // Woodland Park Zoo, Seattle WA
  });

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

  console.log(place.displayName);
  console.log(place.photos[0]);
  // Add the first photo to an img element.
  const photoImg = document.getElementById('image-container');
  photoImg.src = place.photos[0].getURI({maxHeight: 400});
}

Place 類別中的作者屬性

Place 類別會以 AuthorAttribution 例項的形式傳回作者資訊,包括作者姓名、作者 Google 個人資料頁面的 URI,以及作者個人資料相片的 URI。下列程式碼片段顯示如何擷取第一張相片結果的出處資訊。

let name = place.photos[0].authorAttributions[0].displayName;
let attributionUrl = place.photos[0].authorAttributions[0].uri;
let photoUrl = place.photos[0].authorAttributions[0].photoUri;

瞭解詳情