迁移到新的“地点照片”

欧洲经济区 (EEA) 开发者

借助 Place Photos,您可以向网页添加高品质照片内容。本页面介绍了 Place 类(新)和 PlacesService(旧)中的地点照片功能之间的差异,并提供了一些代码段以供比较。

  • PlacesService(旧版)对于任何 getDetails() 请求,如果请求中指定了 photos 字段,则会返回一个最多包含 10 个 PlacePhoto 对象的数组,作为 PlaceResult 对象的一部分。对于 textSearch()nearbySearch(),如果存在第一个地点照片,则默认返回该照片。
  • 如果请求中指定了 photos 字段,Place 类会返回一个最多包含 10 个 Photo 对象的数组,作为 fetchFields() 请求的一部分。

下表列出了 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,以及 namephotos 字段。然后,在检查服务状态后,系统会在页面上显示第一张照片。 实例化 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(),其中指定了 displayNamephotos 字段。 然后,页面上会显示获得第一名的照片。使用 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;

了解详情