地點相片可讓您在網頁中加入高品質的相片內容。本頁面說明 Place 類別 (新版) 和 PlacesService (舊版) 中地點相片功能的差異,並提供一些程式碼片段以供比較。
- PlacesService(舊版) 會在任何- getDetails()要求中,將最多 10 個- PlacePhoto物件的陣列做為- PlaceResult物件的一部分傳回,前提是要求中已指定- photos欄位。如果是- textSearch()和- nearbySearch(),系統預設會傳回第一個地點相片 (如有)。
- 如果要求中指定了 photos欄位,Place類別會在fetchFields()要求中傳回最多 10 個Photo物件的陣列。
下表列出 Place 類別和 PlacesService 在使用地點相片時的一些主要差異:
| PlacesService(舊版) | Place(新) | 
|---|---|
| PlacePhoto介面 | Photo類別 | 
| PlacePhoto會以字串形式傳回html_attributions。 | Photo會傳回AuthorAttribution例項。 | 
| 方法需要使用回呼來處理結果物件和 google.maps.places.PlacesServiceStatus回應。 | 使用 Promise,並以非同步方式運作。 | 
| 方法需要進行 PlacesServiceStatus檢查。 | 不需要檢查狀態,可使用標準錯誤處理程序。 瞭解詳情。 | 
| 必須使用地圖或 div 元素例項化 PlacesService。 | 您可以在需要時例項化 Place,不必參照地圖或網頁元素。 | 
程式碼比較
本節會比較地點相片的程式碼,說明 Places 服務和 Place 類別之間的差異。程式碼片段會顯示在各個 API 上要求地點相片所需的程式碼。
地點服務 (舊版)
下列程式碼片段顯示如何使用 PlacesService 傳回相片,並在網頁上顯示第一張相片結果。在本範例中,地點詳細資料要求會指定地點 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;