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,
  });
}