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

欧州経済領域(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,
  });
}

その他の情報