API dữ liệu tự động hoàn thành địa điểm

API dữ liệu tự động hoàn thành địa điểm cho phép bạn tìm nạp thông tin dự đoán về địa điểm theo phương thức lập trình, để tạo ra trải nghiệm tự động hoàn thành tuỳ chỉnh với mức độ kiểm soát tốt hơn so với tiện ích tự động hoàn thành. Trong hướng dẫn này, bạn sẽ tìm hiểu cách sử dụng API dữ liệu tự động hoàn thành theo địa điểm để tạo yêu cầu tự động hoàn thành dựa trên cụm từ tìm kiếm của người dùng.

Ví dụ sau đây cho thấy một quá trình tích hợp kiểu phía trước đơn giản. Nhập cụm từ tìm kiếm rồi nhấp để chọn kết quả mà bạn muốn.

Yêu cầu tự động hoàn thành

Yêu cầu tự động hoàn thành sẽ nhận một chuỗi thông tin đầu vào của cụm từ tìm kiếm và trả về một danh sách các thông tin dự đoán về địa điểm. Để đưa ra yêu cầu tự động hoàn thành, hãy gọi fetchAutocompleteSuggestions() và chuyển yêu cầu với các thuộc tính cần thiết. Thuộc tính input chứa chuỗi cần tìm kiếm. Trong một ứng dụng thông thường, giá trị này sẽ được cập nhật khi người dùng nhập một truy vấn. Yêu cầu phải bao gồm một sessionToken (dùng cho mục đích thanh toán).

Đoạn mã sau đây cho thấy việc tạo nội dung yêu cầu và thêm mã thông báo phiên, sau đó gọi fetchAutocompleteSuggestions() để lấy danh sách 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;

Giới hạn các cụm từ gợi ý của tính năng Tự động hoàn thành

Theo mặc định, tính năng Tự động hoàn thành địa điểm sẽ hiển thị mọi loại địa điểm, thiên về các cụm từ gợi ý gần vị trí của người dùng và tìm nạp mọi trường dữ liệu có sẵn cho địa điểm mà người dùng đã chọn. Đặt các tuỳ chọn Tự động hoàn thành về địa điểm để đưa ra thông tin dự đoán phù hợp hơn bằng cách hạn chế hoặc xu hướng kết quả.

Việc hạn chế kết quả sẽ khiến tiện ích Tự động hoàn thành bỏ qua mọi kết quả nằm ngoài vùng hạn chế. Một phương pháp phổ biến là giới hạn kết quả ở ranh giới bản đồ. Kết quả xu hướng giúp tiện ích Tự động hoàn thành hiển thị kết quả trong khu vực được chỉ định, nhưng một số kết quả phù hợp có thể nằm ngoài khu vực đó.

Sử dụng thuộc tính origin để chỉ định điểm gốc dùng để tính khoảng cách trắc địa tới điểm đến. Nếu giá trị này bị bỏ qua, thì hàm sẽ không trả về khoảng cách.

Sử dụng thuộc tính includedPrimaryTypes để chỉ định tối đa 5 loại địa điểm. Nếu bạn không chỉ định loại nào, thì hàm sẽ trả về tất cả các loại địa điểm.

Xem tài liệu tham khảo API

Lấy thông tin chi tiết về địa điểm

Để trả về một đối tượng Place từ kết quả dự đoán địa điểm, trước tiên hãy gọi toPlace(), sau đó gọi fetchFields() trên đối tượng Place thu được (mã phiên của thông tin dự đoán về địa điểm sẽ tự động được đưa vào). Việc gọi fetchFields() sẽ kết thúc phiên tự động hoàn thành.

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;

Mã thông báo phiên

Mã thông báo phiên sẽ nhóm các giai đoạn truy vấn và lựa chọn trong tính năng tự động hoàn thành tìm kiếm của người dùng thành một phiên riêng biệt cho mục đích thanh toán. Phiên bắt đầu khi người dùng bắt đầu nhập. Phiên kết thúc khi người dùng chọn một địa điểm và thực hiện lệnh gọi đến phần Thông tin chi tiết về địa điểm.

Để tạo mã thông báo phiên mới và thêm mã đó vào yêu cầu, hãy tạo một bản sao của AutocompleteSessionToken, sau đó đặt thuộc tính sessionToken của yêu cầu để sử dụng các mã thông báo như minh hoạ trong đoạn mã sau:

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

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

Một phiên kết thúc khi fetchFields() được gọi. Sau khi tạo thực thể Place, bạn không cần truyền mã thông báo phiên cho fetchFields() vì quy trình này được xử lý tự động.

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

Tạo mã thông báo phiên cho phiên tiếp theo bằng cách tạo một phiên bản mới của AutocompleteSessionToken.

Đề xuất về mã thông báo phiên:

  • Sử dụng mã thông báo phiên cho tất cả các lệnh gọi Tự động hoàn thành địa điểm.
  • Tạo mã thông báo mới cho mỗi phiên hoạt động.
  • Truyền một mã thông báo phiên duy nhất cho mỗi phiên mới. Nếu bạn sử dụng cùng một mã thông báo cho nhiều phiên, thì mỗi yêu cầu sẽ bị tính phí riêng.

Bạn có thể tuỳ ý bỏ qua mã thông báo phiên tự động hoàn thành khỏi yêu cầu. Nếu bạn bỏ qua mã thông báo phiên, thì mỗi yêu cầu sẽ được tính phí riêng, kích hoạt SKU Tự động hoàn thành – Theo yêu cầu. Nếu bạn sử dụng lại mã thông báo phiên, thì phiên đó sẽ bị coi là không hợp lệ và các yêu cầu sẽ được tính phí như thể không có mã thông báo phiên nào được cung cấp.

Ví dụ:

Khi người dùng nhập một truy vấn, cứ sau vài lần nhấn phím (không phải mỗi ký tự), một yêu cầu tự động hoàn thành sẽ được gọi và một danh sách kết quả có thể nhận được sẽ được trả về. Khi người dùng đưa ra lựa chọn trong danh sách kết quả, yêu cầu đó sẽ được tính là một yêu cầu và tất cả các yêu cầu đưa ra trong quá trình tìm kiếm sẽ được nhóm lại và tính là một yêu cầu duy nhất. Nếu người dùng chọn một địa điểm, hệ thống sẽ không tính phí cho cụm từ tìm kiếm và chỉ tính phí đối với yêu cầu Dữ liệu địa điểm. Nếu người dùng không đưa ra lựa chọn trong vòng vài phút đầu phiên, thì chỉ có cụm từ tìm kiếm bị tính phí.

Từ góc độ của một ứng dụng, luồng sự kiện diễn ra như sau:

  1. Một người dùng bắt đầu nhập một cụm từ tìm kiếm để tìm kiếm " Paris, Pháp".
  2. Khi phát hiện hoạt động đầu vào của người dùng, ứng dụng sẽ tạo một mã thông báo phiên mới là "Mã thông báo A".
  3. Khi người dùng nhập, API sẽ đưa ra một yêu cầu tự động hoàn thành cứ vài ký tự một lần, hiển thị danh sách các kết quả có thể có mới cho mỗi loại:
    "P"
    "Par"
    " Paris",
    " Paris, Fr"
  4. Khi người dùng đưa ra lựa chọn:
    • Tất cả các yêu cầu phát sinh từ truy vấn sẽ được nhóm lại và thêm vào phiên được biểu thị bằng "Mã thông báo A", dưới dạng một yêu cầu duy nhất.
    • Lựa chọn của người dùng được tính là một yêu cầu Thông tin chi tiết về địa điểm và được thêm vào phiên được đại diện bằng "Mã thông báo A".
  5. Phiên kết thúc và ứng dụng sẽ loại bỏ "Mã thông báo A".
Tìm hiểu về cách tính phí cho các phiên hoạt động

Đoạn mã mẫu hoàn chỉnh

Phần này chứa các ví dụ hoàn chỉnh minh hoạ cách sử dụng API dữ liệu tự động hoàn thành dành cho địa điểm .

Đặt cụm từ gợi ý của tính năng tự động hoàn thành

Ví dụ sau minh hoạ việc gọi fetchAutocompleteSuggestions() cho dữ liệu đầu vào "Tadi", sau đó gọi toPlace() trên kết quả dự đoán đầu tiên, tiếp theo là lệnh gọi đến fetchFields() để nhận thông tin chi tiết về địa điểm.

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>

    <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>

Thử dùng mẫu

Đặt tính năng tự động hoàn thành ở phía trước với các phiên

Ví dụ này minh hoạ việc gọi fetchAutocompleteSuggestions() dựa trên các truy vấn của người dùng, hiển thị danh sách các địa điểm được dự đoán trong phản hồi và cuối cùng là truy xuất thông tin chi tiết về địa điểm cho địa điểm đã chọn. Ví dụ này cũng minh hoạ việc sử dụng mã thông báo phiên để nhóm một truy vấn của người dùng với yêu cầu Thông tin chi tiết về địa điểm cuối cùng.

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>

    <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>

Thử dùng mẫu