新しい Place Autocomplete に移行する

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

Place Autocomplete は、Maps JavaScript API のプレイス ライブラリの機能です。予測入力を使用すると、Google マップの検索フィールドの逐次検索機能をアプリケーションに組み込むことができます。

このページでは、以前の Place Autocomplete 機能と新しい Place Autocomplete 機能の違いについて説明します。どちらのバージョンでも、予測入力を統合する方法は、大きく分けて次の 2 つです。

予測入力のプログラマティック インターフェース

次の表に、Places Autocomplete Service(従来版)と Autocomplete Data API(新版)でプログラムによる Place Autocomplete を使用する場合の主な違いを示します。

PlacesService(レガシー) Place(新規)
Place Autocomplete サービスのリファレンス 予測入力データ(新規)のリファレンス
AutocompletionRequest AutocompleteRequest
AutocompleteService.getPlacePredictions AutocompleteSuggestion.fetchAutocompleteSuggestions
AutocompletePrediction PlacePrediction
メソッドでは、結果オブジェクトと PlacesServiceStatus レスポンスを処理するためにコールバックを使用する必要があります。 Promise を使用し、非同期で動作します。
メソッドには PlacesServiceStatus チェックが必要です。 必要なステータス チェックはありません。標準のエラー処理を使用できます。 詳細
プレイス データ フィールドは、Autocomplete インスタンスの作成時にオプションとして設定されます。 プレイスデータ フィールドは、後で fetchFields() が呼び出されたときに設定されます。
クエリ予測がサポートされています(SearchBox のみ)。 クエリ予測は Autocomplete クラスでは使用できません。
場所のタイプと場所のデータ フィールドの固定セットに限定されます。 場所の種類と場所のデータ フィールドの選択肢が拡大。

以下は、以前の Autocomplete API と新しい Autocomplete API の両方で使用されます。

コードの比較(プログラマティック)

このセクションでは、予測入力のコードを比較して、プログラム インターフェースにおける Places Service と Place クラスの違いを説明します。

予測入力候補を取得する(従来版)

以前の Places Service を使用すると、予測入力候補をプログラムで取得できます。これにより、Autocomplete クラスよりもユーザー インターフェースを細かく制御できます。次の例では、「par」に対して 1 つのリクエストが行われます。AutocompletionRequest は、入力値と、予測をバイアスするための境界のセットで構成されます。この例では、AutocompletePrediction インスタンスのリストが返され、各インスタンスの説明が表示されます。このサンプル関数は、セッション トークンを作成してリクエストに適用します。

function init() {
  const placeInfo = document.getElementById("prediction");
  const service = new google.maps.places.AutocompleteService();
  const placesService = new google.maps.places.PlacesService(placeInfo);
  var sessionToken = new google.maps.places.AutocompleteSessionToken();

  // Define request options.
  let request = {
    input: "par",
    sessionToken: sessionToken,
    bounds: {
      west: -122.44,
      north: 37.8,
      east: -122.39,
      south: 37.78,
    },
  }

  // Display the query string.
  const title = document.getElementById("title");
  title.appendChild(
    document.createTextNode('Place predictions for "' + request.input + '":'),
  );

  // Perform the query and display the results.
  const displaySuggestions = function (predictions, status) {
    // Check the status of the Places Service.
    if (status != google.maps.places.PlacesServiceStatus.OK || !predictions) {
      alert(status);
      return;
    }

    predictions.forEach((prediction) => {
      const li = document.createElement("li");
      li.appendChild(document.createTextNode(prediction.description));
      document.getElementById("results").appendChild(li);
    });

    const placeRequest = {
      placeId: predictions[0].place_id,
      fields: ["name", "formatted_address"],
    };

    placesService.getDetails(placeRequest, (place, status) => {
      if (status == google.maps.places.PlacesServiceStatus.OK && place) {
        placeInfo.textContent = `
          First predicted place: ${place.name} at ${place.formatted_address}`
      }
    });

  };

  // Show the results of the query.
  service.getPlacePredictions(request, displaySuggestions);
}

予測入力候補を取得する(新版)

新しい Place クラスでは、予測入力候補をプログラムで取得することもできます。これにより、PlaceAutocompleteElement クラスよりもユーザー インターフェースを細かく制御できます。次の例では、「par」に対して 1 つのリクエストが行われます。AutocompleteRequest は、入力値と、予測をバイアスするための境界のセットで構成されます。この例では、placePrediction インスタンスのリストを返し、それぞれの説明を表示します。このサンプル関数は、セッション トークンを作成してリクエストに適用します。

async function init() {
  let sessionToken = new google.maps.places.AutocompleteSessionToken();

  // Define request options.
  let request = {
    input: "par",
    sessionToken: sessionToken,
    locationBias: {
      west: -122.44,
      north: 37.8,
      east: -122.39,
      south: 37.78,
    },
  };

  // Display the query string.
  const title = document.getElementById("title");
  title.appendChild(
    document.createTextNode('Place predictions for "' + request.input + '":'),
  );

  // Perform the query and display the results.
  const { suggestions } =
    await google.maps.places.AutocompleteSuggestion.fetchAutocompleteSuggestions(request);

  const resultsElement = document.getElementById("results");

  for (let suggestion of suggestions) {
    const placePrediction = suggestion.placePrediction;
    const listItem = document.createElement("li");

    listItem.appendChild(
      document.createTextNode(placePrediction.text.text),
    );

    resultsElement.appendChild(listItem);
  }

  // Show the first predicted place.
  let place = suggestions[0].placePrediction.toPlace();

  await place.fetchFields({
    fields: ["displayName", "formattedAddress"],
  });

  const placeInfo = document.getElementById("prediction");

  placeInfo.textContent = `
    First predicted place: ${place.displayName} at ${place.formattedAddress}`
}

Place Autocomplete ウィジェット

次の表に、Places サービス(従来版)と Place クラス(新規)における予測入力ウィジェットの使用方法の主な違いを示します。

プレイス サービス(従来版) Place(新規)
場所の予測用の Autocomplete クラス。 場所の予測用の PlaceAutocompleteElement クラス。
クエリ予測用の SearchBox クラス。
クエリ予測は Autocomplete クラスでは使用できません。
ローカライズされるのは、デフォルトの入力プレースホルダ テキストのみです。 テキスト入力のプレースホルダ、予測リストのロゴ、場所の候補はすべて、地域的ローカライズに対応しています。
ウィジェットは、setBounds() または autocomplete.bindTo() を使用して、指定された境界に検索を制限(バイアス)し、strictBounds を使用して、指定された境界に結果を制限します。 ウィジェットは、locationBias プロパティを使用して、指定された境界に結果をバイアスし、locationRestriction プロパティを使用して、指定された境界に検索を制限します。
ウィジェットは、標準の HTML 入力要素を使用してのみ統合できます。 ウィジェットは、標準の HTML 入力要素または gmp-place-autocomplete 要素を使用して統合できます。
ウィジェットを使用する場合、ユーザーは有効でないもの(「bisneyland」など)をリクエストする可能性があります。このケースは明示的に処理する必要があります。 ウィジェットは、提供された候補の結果のみを返し、任意の値をリクエストすることはできません。そのため、無効なリクエストを処理する必要はありません。
従来の PlaceResult インスタンスを返します。 Place インスタンスを返します。
Place データ フィールドは、Autocomplete オブジェクトのオプションとして設定されます。 ユーザーが選択を行い、fetchFields() が呼び出されると、場所のデータ フィールドが設定されます。
場所のタイプと場所のデータ フィールドの固定セットに限定されます。 場所の種類と場所のデータ フィールドの選択肢が拡大。

コードの比較(ウィジェット)

このセクションでは、予測入力のコードを比較して、以前の Place Autocomplete ウィジェットと新しい Place Autocomplete 要素の違いを説明します。

Place Autocomplete ウィジェット(従来版)

Places Service には、2 種類の予測入力ウィジェットが用意されており、それぞれ Autocomplete クラスと SearchBox クラスで指定することができます。各ウィジェットは、地図コントロールとして地図に追加することも、ウェブページに直接埋め込むこともできます。次のコード例は、Autocomplete ウィジェットを地図コントロールとして埋め込む方法を示しています。

  • Autocomplete ウィジェット コンストラクタは次の 2 つの引数を取ります。
    • タイプが text の HTML input 要素。これは、予測入力サービスが監視し、結果を付加する入力フィールドです。
    • オプションの AutocompleteOptions 引数。クエリを制限する追加のオプションを指定できます。
  • 境界を設定するには、autocomplete.bindTo() を呼び出して、Autocomplete インスタンスを地図に明示的にバインドします。
  • 予測入力のオプションで、場所のデータ フィールドを指定します。
function initMap() {
  const map = new google.maps.Map(document.getElementById("map"), {
    center: { lat: 40.749933, lng: -73.98633 },
    zoom: 13,
    mapTypeControl: false,
  });
  const card = document.getElementById("pac-card");
  const input = document.getElementById("pac-input");
  const options = {
    fields: ["formatted_address", "geometry", "name"],
    strictBounds: false,
  };

  map.controls[google.maps.ControlPosition.TOP_LEFT].push(card);

  const autocomplete = new google.maps.places.Autocomplete(input, options);

  // Bind the map's bounds (viewport) property to the autocomplete object,
  // so that the autocomplete requests use the current map bounds for the
  // bounds option in the request.
  autocomplete.bindTo("bounds", map);

  const infowindow = new google.maps.InfoWindow();
  const infowindowContent = document.getElementById("infowindow-content");

  infowindow.setContent(infowindowContent);

  const marker = new google.maps.Marker({
    map,
    anchorPoint: new google.maps.Point(0, -29),
  });

  autocomplete.addListener("place_changed", () => {
    infowindow.close();
    marker.setVisible(false);

    const place = autocomplete.getPlace();

    if (!place.geometry || !place.geometry.location) {
      // User entered the name of a Place that was not suggested and
      // pressed the Enter key, or the Place Details request failed.
      window.alert("No details available for input: '" + place.name + "'");
      return;
    }

    // If the place has a geometry, then present it on a map.
    if (place.geometry.viewport) {
      map.fitBounds(place.geometry.viewport);
    } else {
      map.setCenter(place.geometry.location);
      map.setZoom(17);
    }

    marker.setPosition(place.geometry.location);
    marker.setVisible(true);
    infowindowContent.children["place-name"].textContent = place.name;
    infowindowContent.children["place-address"].textContent =
      place.formatted_address;
    infowindow.open(map, marker);
  });
}

Place Autocomplete ウィジェット(新版)

Place クラスには PlaceAutocompleteElement が用意されています。これは HTMLElement のサブクラスで、地図コントロールとして地図に追加したり、ウェブページに直接埋め込んだりできる UI コンポーネントを提供します。次のコード例は、PlaceAutocompleteElement ウィジェットを地図コントロールとして埋め込む方法を示しています。

Place Autocomplete ウィジェットには、次のような改良点が盛り込まれています。

  • Autocomplete ウィジェットの UI で、テキスト入力のプレースホルダ、予測リストのロゴ、場所の候補に関する地域的ローカライズ(RTL 言語対応を含む)がサポートされました。
  • スクリーン リーダーやキーボード操作のサポートなど、ユーザー補助機能が強化されました。
  • Autocomplete ウィジェットが返す新しい Place クラスにより、返されたオブジェクトの処理が簡素化されます。
  • モバイル デバイスと小さな画面に対するサポートが強化されました。
  • パフォーマンスとグラフィックの外観が向上しました。

実装の主な違いは次のとおりです。

  • PlaceAutocompleteElement は独自の入力フィールドを提供し、HTML または JavaScript を使用してページに直接挿入されます(既存の入力要素が提供されるわけではありません)。
  • クエリ予測は Autocomplete クラスでは使用できません。
  • PlaceAutocompleteElement は PlaceAutocompleteElementOptions を使用して作成されます。
    • プレイス データ フィールドは、選択時(fetchFields() が呼び出されたとき)に指定されます。
  • locationBounds オプションまたは locationRestriction オプションを使用して境界を設定します。
let map;
let marker;
let infoWindow;

async function initMap() {
  // Request needed libraries.
  const [{ Map }, { AdvancedMarkerElement }] = await Promise.all([
    google.maps.importLibrary("marker"),
    google.maps.importLibrary("places"),
  ]);

  // Initialize the map.
  map = new google.maps.Map(document.getElementById("map"), {
    center: { lat: 40.749933, lng: -73.98633 },
    zoom: 13,
    mapId: "4504f8b37365c3d0",
    mapTypeControl: false,
  });

  const placeAutocomplete =
    new google.maps.places.PlaceAutocompleteElement({
      locationRestriction: map.getBounds(),
    });

  placeAutocomplete.id = "place-autocomplete-input";
  const card = document.getElementById("place-autocomplete-card");

  card.appendChild(placeAutocomplete);
  map.controls[google.maps.ControlPosition.TOP_LEFT].push(card);

  // Create the marker and infowindow.
  marker = new google.maps.marker.AdvancedMarkerElement({
    map,
  });
  infoWindow = new google.maps.InfoWindow({});

  // Add the gmp-select listener, and display the results on the map.
  placeAutocomplete.addEventListener("gmp-select", async ( event ) => {
    const place = event.placePrediction.toPlace();
    await place.fetchFields({
      fields: ["displayName", "formattedAddress", "location", "viewport"],
    });
    // If the place has a geometry, then present it on a map.
    if (place.viewport) {
      map.fitBounds(place.viewport);
    } else {
      map.setCenter(place.location);
      map.setZoom(17);
    }

    let content =
      '<div id="infowindow-content">' +
      '<span id="place-displayname" class="title">' +
      place.displayName +
      '</span><br />' +
      '<span id="place-address">' +
      place.formattedAddress +
      '</span>' +
      '</div>';

    updateInfoWindow(content, place.location);
    marker.position = place.location;
  });
}

// Helper function to create an info window.
function updateInfoWindow(content, center) {
  infoWindow.setContent(content);
  infoWindow.setPosition(center);
  infoWindow.open({
    map,
    anchor: marker,
    shouldFocus: false,
  });
}