Place Autocomplete は、Maps JavaScript API のプレイス ライブラリの機能です。予測入力を使用すると、Google マップの検索フィールドの逐次検索機能をアプリケーションに組み込むことができます。
このページでは、以前の Place Autocomplete 機能と新しい Place Autocomplete 機能の違いについて説明します。どちらのバージョンでも、予測入力を統合する方法は次の 2 つです。
- プログラム インターフェース: 予測入力エクスペリエンスのカスタマイズと制御を強化したいデベロッパー向け。
- Place Autocomplete ウィジェット: 地図やウェブページに埋め込むことができる検索バー。
予測入力のプログラム インターフェース
次の表に、Places Autocomplete Service(以前のサービス)と Autocomplete Data API(新しいサービス)のプログラムによる Place Autocomplete の使用における主な違いをまとめます。
| PlacesService(レガシー) | Place(新規) | 
|---|---|
| Places Autocomplete Service リファレンス | 予測入力データ(新規)のリファレンス | 
| 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 Autocomplete サービスの予測を取得する
- Place Autocomplete の例
- セッション トークン
- AutocompletionRequestリファレンス
- AutocompletePredictionリファレンス
予測入力候補を取得する(新規)
新しい 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 Data API
- Place Autocomplete のデータ予測の例
- Place Autocomplete のデータ セッションの例
- セッション トークン
- AutocompleteRequestインターフェース リファレンス
- AutocompleteSuggestionクラス リファレンス
- PlacePredictionクラス リファレンス
Place Autocomplete ウィジェット
次の表に、Places サービス(レガシー)と Place クラス(新規)でのオートコンプリート ウィジェットの使用における主な違いをいくつか示します。
| プレイス サービス(従来版) | プレイス(新規) | 
|---|---|
| 場所の予測用の Autocompleteクラス。 | 場所の予測用の PlaceAutocompleteElementクラス。 | 
| クエリ予測用の SearchBoxクラス | クエリ予測は Autocompleteクラスでは使用できません。 | 
| ローカライズされるのは、デフォルトの入力プレースホルダ テキストのみです。 | テキスト入力のプレースホルダ、予測リストのロゴ、場所の候補はすべて、地域的ローカライズに対応しています。 | 
| ウィジェットは、 setBounds()またはautocomplete.bindTo()を使用して検索を指定した境界に制限(バイアス)し、strictBoundsを使用して結果を指定した境界に制限します。 | ウィジェットは、 locationBiasプロパティを使用して結果を特定の境界にバイアスし、locationRestrictionプロパティを使用して検索を特定の境界に制限します。 | 
| ウィジェットは、標準の HTML 入力要素を使用してのみ統合できます。 | ウィジェットは、標準の HTML 入力要素または gmp-place-autocomplete要素を使用して統合できます。 | 
| ウィジェットを使用する際、ユーザーが無効なリクエスト(「bisneyland」など)を行う可能性があります。このケースは明示的に処理する必要があります。 | ウィジェットは、指定された候補の結果のみを返し、任意の値をリクエストすることはできません。そのため、無効なリクエストを処理する必要はありません。 | 
| 以前の PlaceResultインスタンスを返します。 | Placeインスタンスを返します。 | 
| 場所データ フィールドは、 Autocompleteオブジェクトのオプションとして設定されます。 | ユーザーが選択を行い、 fetchFields()が呼び出されると、場所のデータ フィールドが設定されます。 | 
| 場所タイプと場所データ フィールドの固定セットに限定されます。 | 場所の種類と場所のデータ フィールドの選択肢が拡大されます。 | 
コードの比較(ウィジェット)
このセクションでは、オートコンプリートのコードを比較して、以前の Place Autocomplete ウィジェットと新しい Place Autocomplete 要素の違いを説明します。
Place Autocomplete ウィジェット(従来版)
Places Service には、2 種類の予測入力ウィジェットが用意されており、それぞれ Autocomplete クラスと SearchBox クラスで指定することができます。各ウィジェットは、地図コントロールとして地図に追加するか、ウェブページに直接埋め込むことができます。次のコード例は、Autocomplete ウィジェットを地図コントロールとして埋め込む方法を示しています。
- Autocompleteウィジェット コンストラクタは次の 2 つの引数を取ります。- タイプが textの HTMLinput要素。これは、予測入力サービスが監視し、結果を付加する入力フィールドです。
- 省略可能な 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 を提供します。これは、地図に地図コントロールとして追加したり、ウェブページに直接埋め込んだりできる UI コンポーネントを提供する HTMLElement サブクラスです。次のコード例は、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 ( place ) => {
    const place = event.placePrediction.toPlace();
    await place.fetchFields({
      fields: ["displayName", "formattedAddress", "location"],
    });
    // 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,
  });
}
- Place Autocomplete ウィジェット(プレビュー)のドキュメント
- Place Autocomplete ウィジェットの例
- Place Autocomplete の要素の例
- PlaceAutocompleteElementクラス リファレンス