Place Autocomplete Data API

Place Autocomplete Data API を使用すると、場所の候補をプログラムで取得して、オートコンプリート ウィジェットよりもきめ細かく制御した、カスタマイズされたオートコンプリートを作成できます。このガイドでは、Place Autocomplete Data API を使用して、ユーザーのクエリに基づいてオートコンプリート リクエストを行う方法について説明します。

次の例は、単純な予測入力統合を示しています。検索クエリを入力し、結果をクリックして選択します。

Autocomplete リクエスト

オートコンプリート リクエストは、クエリ文字列を受け取り、場所の予測リストを返します。オートコンプリート リクエストを作成するには、fetchAutocompleteSuggestions() を呼び出し、必要なプロパティを含むリクエストを渡します。input プロパティには、検索する文字列を指定します。一般的なアプリケーションでは、ユーザーがクエリを入力すると、この値が更新されます。リクエストには、課金目的で使用される sessionToken を含める必要があります。

次のスニペットは、リクエスト本文を作成してセッション トークンを追加し、fetchAutocompleteSuggestions() を呼び出して PlacePrediction のリストを取得する方法を示しています。

// Add an initial request body.
let request = {
  input: "Tadi",
  locationRestriction: {
    west: -122.44,
    north: 37.8,
    east: -122.39,
    south: 37.78,
  },
  origin: { lat: 37.7893, lng: -122.4039 },
  includedPrimaryTypes: ["restaurant"],
  language: "en-US",
  region: "us",
};
// Create a session token.
const token = new AutocompleteSessionToken();

// Add the token to the request.
// @ts-ignore
request.sessionToken = token;

予測入力候補を制限する

デフォルトでは、Place Autocomplete はすべてのタイプの場所を表示します。ユーザーの現在地に近い予測を優先し、ユーザーが選択した場所について利用可能なすべてのデータ フィールドを取得します。Place Autocomplete のオプションを設定すると、検索結果を制限したりバイアスをかけたりして、より関連性の高い候補を提示できます。

結果を制限すると、Autocomplete ウィジェットは制限領域外の結果を無視します。一般的な制限方法は、結果を地図の境界内のみに限定することです。バイアスを設定すると、指定されたエリア内の結果が優先的に表示されますが、エリア外に一致する結果が含まれる場合もあります。

origin プロパティを使用して、目的地までの測地線距離を計算する出発地を指定します。この値を省略すると、距離は返されません。

includedPrimaryTypes プロパティを使用して、最大 5 つの場所タイプを指定します。タイプが指定されていない場合は、すべてのタイプの場所が返されます。

API リファレンスを確認する

Place Details を取得する

場所予測の結果から Place オブジェクトを返すには、まず toPlace() を呼び出し、結果の Place オブジェクトで fetchFields() を呼び出します(場所の予測結果からのセッション ID が自動的に含まれます)。fetchFields() を呼び出すと、オートコンプリート セッションが終了します。

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

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

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

placeInfo.textContent =
  "First predicted place: " +
  place.displayName +
  ": " +
  place.formattedAddress;

セッション トークン

セッション トークンは、ユーザーのオートコンプリート検索のクエリフェーズと選択フェーズを、課金のために個別のセッションにグループ化します。ユーザーが入力を開始するとセッションが開始されます。ユーザーが場所を選択し、Place Details が呼び出されると、セッションは終了します。

新しいセッション トークンを作成してリクエストに追加するには、AutocompleteSessionToken のインスタンスを作成し、次のスニペットに示すように、リクエストの sessionToken プロパティを設定して、トークンを使用します。

// Create a session token.
const token = new AutocompleteSessionToken();

// Add the token to the request.
// @ts-ignore
request.sessionToken = token;

fetchFields() が呼び出されるとセッションが終了します。Place インスタンスの作成後は、セッション トークンが自動的に処理されるため、fetchFields() に渡す必要はありません。

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

AutocompleteSessionToken の新しいインスタンスを作成することで、次のセッションのセッション トークンを作成します。

セッション トークンの推奨事項:

  • すべての Place Autocomplete 呼び出しにセッション トークンを使用します。
  • セッションごとに新しいトークンを生成します。
  • 新しいセッションごとに一意のセッション トークンを渡します。同じトークンを複数のセッションで使用した場合は、リクエストごとに課金されます。

必要に応じて、リクエストからオートコンプリート セッション トークンを省略できます。セッション トークンを省略すると、各リクエストが個別に課金され、Autocomplete - Per Request SKU がトリガーされます。セッション トークンを再利用すると、そのセッションは無効とみなされ、セッション トークンを渡さなかった場合と同様にリクエストが課金されます。

ユーザーがクエリを入力すると、(文字単位ではなく)数キー入力ごとにオートコンプリート リクエストが呼び出され、候補のリストが返されます。ユーザーが結果リストから選択を行うと、その選択がリクエストとしてカウントされ、検索中に行われたすべてのリクエストがバンドルされて 1 つのリクエストとしてカウントされます。ユーザーが場所を選択すると、その検索クエリは料金なしで利用できます。また、料金が発生するのはプレイス データ リクエストのみです。セッションの開始から数分以内にユーザーが選択を行わなかった場合は、検索クエリのみが課金されます。

アプリの観点からは、イベントのフローは次のようになります。

  1. ユーザーがクエリの入力を開始し、「Paris, France」を検索します。
  2. アプリはユーザー入力を検出すると、新しいセッション トークン「トークン A」を作成します。
  3. ユーザーが入力を始めると、API が数文字ごとにオートコンプリート リクエストを実行し、それぞれの候補の結果の新しいリストを表示します。
    "P"
    "Par"
    "Paris",
    "Paris, Fr"
  4. ユーザーが選択したら、以下の操作を行います。
    • このクエリによるすべてのリクエストはグループ化され、「トークン A」で表されるセッションに 1 つのリクエストとして追加されます。
    • ユーザーの選択は Place Detail リクエストとしてカウントされ、「トークン A」で表されるセッションに追加されます。
  5. セッションが終了し、アプリは「トークン A」を破棄します。
セッションの課金方法の詳細

コードサンプルの全文

このセクションでは、Place Autocomplete Data API の使用方法を示す完全な例を紹介します。

Place Autocomplete の予測

次の例では、入力「Tadi」に対して fetchAutocompleteSuggestions() を呼び出し、最初の予測結果に対して toPlace() を呼び出してから、fetchFields() を呼び出して Place Details を取得しています。

TypeScript

/**
 * Demonstrates making a single request for Place predictions, then requests Place Details for the first result.
 */
async function init() {
    // @ts-ignore
    const { Place, AutocompleteSessionToken, AutocompleteSuggestion } = await google.maps.importLibrary("places") as google.maps.PlacesLibrary;

    // Add an initial request body.
    let request = {
        input: "Tadi",
        locationRestriction: { west: -122.44, north: 37.8, east: -122.39, south: 37.78 },
        origin: { lat: 37.7893, lng: -122.4039 },
        includedPrimaryTypes: ["restaurant"],
        language: "en-US",
        region: "us",
    };

    // Create a session token.
    const token = new AutocompleteSessionToken();
    // Add the token to the request.
    // @ts-ignore
    request.sessionToken = token;
    // Fetch autocomplete suggestions.
    const { suggestions } = await AutocompleteSuggestion.fetchAutocompleteSuggestions(request);

    const title = document.getElementById('title') as HTMLElement;
    title.appendChild(document.createTextNode('Query predictions for "' + request.input + '":'));

    for (let suggestion of suggestions) {
        const placePrediction = suggestion.placePrediction;

        // Create a new list element.
        const listItem = document.createElement('li');
        const resultsElement = document.getElementById("results") as HTMLElement;
        listItem.appendChild(document.createTextNode(placePrediction.text.toString()));
        resultsElement.appendChild(listItem);
    }

    let place = suggestions[0].placePrediction.toPlace(); // Get first predicted place.
    await place.fetchFields({
        fields: ['displayName', 'formattedAddress'],
    });

    const placeInfo = document.getElementById("prediction") as HTMLElement;
    placeInfo.textContent = 'First predicted place: ' + place.displayName + ': ' + place.formattedAddress;

}

init();

JavaScript

/**
 * Demonstrates making a single request for Place predictions, then requests Place Details for the first result.
 */
async function init() {
  // @ts-ignore
  const { Place, AutocompleteSessionToken, AutocompleteSuggestion } =
    await google.maps.importLibrary("places");
  // Add an initial request body.
  let request = {
    input: "Tadi",
    locationRestriction: {
      west: -122.44,
      north: 37.8,
      east: -122.39,
      south: 37.78,
    },
    origin: { lat: 37.7893, lng: -122.4039 },
    includedPrimaryTypes: ["restaurant"],
    language: "en-US",
    region: "us",
  };
  // Create a session token.
  const token = new AutocompleteSessionToken();

  // Add the token to the request.
  // @ts-ignore
  request.sessionToken = token;

  // Fetch autocomplete suggestions.
  const { suggestions } =
    await AutocompleteSuggestion.fetchAutocompleteSuggestions(request);
  const title = document.getElementById("title");

  title.appendChild(
    document.createTextNode('Query predictions for "' + request.input + '":'),
  );

  for (let suggestion of suggestions) {
    const placePrediction = suggestion.placePrediction;
    // Create a new list element.
    const listItem = document.createElement("li");
    const resultsElement = document.getElementById("results");

    listItem.appendChild(
      document.createTextNode(placePrediction.text.toString()),
    );
    resultsElement.appendChild(listItem);
  }

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

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

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

  placeInfo.textContent =
    "First predicted place: " +
    place.displayName +
    ": " +
    place.formattedAddress;
}

init();

CSS

/* 
 * Always set the map height explicitly to define the size of the div element
 * that contains the map. 
 */
#map {
  height: 100%;
}

/* 
 * Optional: Makes the sample page fill the window. 
 */
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

HTML

<html>
  <head>
    <title>Place Autocomplete Data API Predictions</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>

    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script type="module" src="./index.js"></script>
  </head>
  <body>
    <div id="title"></div>
    <ul id="results"></ul>
    <p><span id="prediction"></span></p>
    <img
      class="powered-by-google"
      src="https://storage.googleapis.com/geo-devrel-public-buckets/powered_by_google_on_white.png"
      alt="Powered by Google"
    />

    <!-- prettier-ignore -->
    <script>(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})
        ({key: "AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg", v: "weekly"});</script>
  </body>
</html>

サンプルを試す

セッション予測にオートコンプリートを使用する

この例では、ユーザークエリに基づいて fetchAutocompleteSuggestions() を呼び出し、それに応じて予測された場所のリストを表示し、最終的に選択された場所の詳細を取得しています。このサンプルは、セッション トークンを使用してユーザークエリと最終的な Place Details リクエストをグループ化する例も示しています。

TypeScript

let title;
let results;
let input;
let token;

// Add an initial request body.
let request = {
    input: "",
    locationRestriction: { west: -122.44, north: 37.8, east: -122.39, south: 37.78 },
    origin: { lat: 37.7893, lng: -122.4039 },
    includedPrimaryTypes: ["restaurant"],
    language: "en-US",
    region: "us",
};

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

    title = document.getElementById('title');
    results = document.getElementById('results');
    input = document.querySelector("input");
    input.addEventListener("input", makeAcRequest);
    request = refreshToken(request) as any;
}

async function makeAcRequest(input) {
    // Reset elements and exit if an empty string is received.
    if (input.target.value == '') {
        title.innerText = '';
        results.replaceChildren();
        return;
    }

    // Add the latest char sequence to the request.
    request.input = input.target.value;

    // Fetch autocomplete suggestions and show them in a list.
    // @ts-ignore
    const { suggestions } = await google.maps.places.AutocompleteSuggestion.fetchAutocompleteSuggestions(request);

    title.innerText = 'Query predictions for "' + request.input + '"';

    // Clear the list first.
    results.replaceChildren();

    for (const suggestion of suggestions) {
        const placePrediction = suggestion.placePrediction;

        // Create a link for the place, add an event handler to fetch the place.
        const a = document.createElement('a');
        a.addEventListener('click', () => {
            onPlaceSelected(placePrediction.toPlace());
        });
        a.innerText = placePrediction.text.toString();

        // Create a new list element.
        const li = document.createElement('li');
        li.appendChild(a);
        results.appendChild(li);
    }
}

// Event handler for clicking on a suggested place.
async function onPlaceSelected(place) {
    await place.fetchFields({
        fields: ['displayName', 'formattedAddress'],
    });
    let placeText = document.createTextNode(place.displayName + ': ' + place.formattedAddress);
    results.replaceChildren(placeText);
    title.innerText = 'Selected Place:';
    input.value = '';
    refreshToken(request);
}

// Helper function to refresh the session token.
async function refreshToken(request) {
    // Create a new session token and add it to the request.
    token = new google.maps.places.AutocompleteSessionToken();
    request.sessionToken = token;
    return request;
}

declare global {
    interface Window {
      init: () => void;
    }
  }
  window.init = init;

JavaScript

let title;
let results;
let input;
let token;
// Add an initial request body.
let request = {
  input: "",
  locationRestriction: {
    west: -122.44,
    north: 37.8,
    east: -122.39,
    south: 37.78,
  },
  origin: { lat: 37.7893, lng: -122.4039 },
  includedPrimaryTypes: ["restaurant"],
  language: "en-US",
  region: "us",
};

async function init() {
  token = new google.maps.places.AutocompleteSessionToken();
  title = document.getElementById("title");
  results = document.getElementById("results");
  input = document.querySelector("input");
  input.addEventListener("input", makeAcRequest);
  request = refreshToken(request);
}

async function makeAcRequest(input) {
  // Reset elements and exit if an empty string is received.
  if (input.target.value == "") {
    title.innerText = "";
    results.replaceChildren();
    return;
  }

  // Add the latest char sequence to the request.
  request.input = input.target.value;

  // Fetch autocomplete suggestions and show them in a list.
  // @ts-ignore
  const { suggestions } =
    await google.maps.places.AutocompleteSuggestion.fetchAutocompleteSuggestions(
      request,
    );

  title.innerText = 'Query predictions for "' + request.input + '"';
  // Clear the list first.
  results.replaceChildren();

  for (const suggestion of suggestions) {
    const placePrediction = suggestion.placePrediction;
    // Create a link for the place, add an event handler to fetch the place.
    const a = document.createElement("a");

    a.addEventListener("click", () => {
      onPlaceSelected(placePrediction.toPlace());
    });
    a.innerText = placePrediction.text.toString();

    // Create a new list element.
    const li = document.createElement("li");

    li.appendChild(a);
    results.appendChild(li);
  }
}

// Event handler for clicking on a suggested place.
async function onPlaceSelected(place) {
  await place.fetchFields({
    fields: ["displayName", "formattedAddress"],
  });

  let placeText = document.createTextNode(
    place.displayName + ": " + place.formattedAddress,
  );

  results.replaceChildren(placeText);
  title.innerText = "Selected Place:";
  input.value = "";
  refreshToken(request);
}

// Helper function to refresh the session token.
async function refreshToken(request) {
  // Create a new session token and add it to the request.
  token = new google.maps.places.AutocompleteSessionToken();
  request.sessionToken = token;
  return request;
}

window.init = init;

CSS

/* 
 * Always set the map height explicitly to define the size of the div element
 * that contains the map. 
 */
#map {
  height: 100%;
}

/* 
 * Optional: Makes the sample page fill the window. 
 */
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

a {
  cursor: pointer;
  text-decoration: underline;
  color: blue;
}

input {
  width: 300px;
}

HTML

<html>
  <head>
    <title>Place Autocomplete Data API Session</title>
    <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>

    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script type="module" src="./index.js"></script>
  </head>
  <body>
    <input id="input" type="text" placeholder="Search for a place..." />
    <div id="title"></div>
    <ul id="results"></ul>
    <img
      class="powered-by-google"
      src="https://storage.googleapis.com/geo-devrel-public-buckets/powered_by_google_on_white.png"
      alt="Powered by Google"
    />

    <!-- 
      The `defer` attribute causes the script to execute after the full HTML
      document has been parsed. For non-blocking uses, avoiding race conditions,
      and consistent behavior across browsers, consider loading using Promises. See
      https://developers.google.com/maps/documentation/javascript/load-maps-js-api
      for more information.
      -->
    <script
      src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=init&libraries=places&v=weekly"
      defer
    ></script>
  </body>
</html>

サンプルを試す