新しい場所の詳細に移行する

欧州経済領域(EEA)のデベロッパー

Places API は、特定の場所に関する詳細情報を返すことができます。このページでは、Place クラス(新しい)と PlacesService(以前の)で使用される場所の詳細の違いについて説明し、比較用のコード スニペットをいくつか紹介します。次の表に、Place クラスと PlacesService の間で場所の詳細の使用に関する主な違いをまとめます。

PlacesService(レガシー) Place(新規)
getDetails() fetchFields()
PlaceDetailsRequest FetchFieldsRequest
メソッドでは、結果オブジェクトと google.maps.places.PlacesServiceStatus レスポンスを処理するためにコールバックを使用する必要があります。 Promise を使用し、非同期で動作します。
メソッドには PlacesServiceStatus チェックが必要です。 ステータス チェックは不要で、標準のエラー処理を使用できます。詳細
プレイス データ フィールドはスネークケースでフォーマットされます。 プレイス データ フィールドは、キャメルケースでフォーマットされます。
場所タイプ場所データ フィールドの固定セットに限定されます。 定期的に更新される場所のタイプ場所のデータ フィールドの選択肢が拡大されます。

コードの比較

このセクションでは、2 つの類似したコードを比較して、Places Service と 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 クラスを使用して Place Details リクエストを行う方法を示しています。リクエストは非同期で、ステータス チェックは含まれていません(標準のエラー処理を使用できます)。プレイス ID は、リクエスト(fetchFields())の作成に使用される新しい Place インスタンスの作成に使用されます。必要なプレイス データ フィールドは 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,
  });
}

その他の情報