API تکمیل خودکار داده را قرار دهید

Place Autocomplete Data API به شما امکان می‌دهد پیش‌بینی‌های مکان را به صورت برنامه‌نویسی واکشی کنید تا تجربیات تکمیل خودکار سفارشی‌شده را با درجه کنترل بهتری نسبت به ویجت تکمیل خودکار ایجاد کنید. در این راهنما، نحوه استفاده از Place Autocomplete Data API برای ایجاد درخواست های تکمیل خودکار بر اساس درخواست های کاربر را خواهید آموخت.

مثال زیر یک ادغام ساده از نوع پیش رو را نشان می دهد. عبارت جستجوی خود را وارد کنید، سپس برای انتخاب نتیجه مورد نظر کلیک کنید.

تکمیل خودکار درخواست ها

یک درخواست تکمیل خودکار یک رشته ورودی پرس و جو می گیرد و لیستی از پیش بینی های مکان را برمی گرداند. برای ایجاد یک درخواست تکمیل خودکار، 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;

پیش بینی های تکمیل خودکار را محدود کنید

به‌طور پیش‌فرض، «تکمیل خودکار مکان» همه انواع مکان‌ها را ارائه می‌کند که برای پیش‌بینی‌های نزدیک به مکان کاربر تعصب دارند و همه فیلدهای داده موجود را برای مکان انتخابی کاربر واکشی می‌کند. گزینه‌های تکمیل خودکار مکان را برای ارائه پیش‌بینی‌های مرتبط‌تر، با محدود کردن یا سوگیری نتایج، تنظیم کنید.

محدود کردن نتایج باعث می‌شود که ویجت تکمیل خودکار نتایجی را که خارج از محدوده محدودیت هستند نادیده بگیرد. یک روش معمول محدود کردن نتایج به محدوده نقشه است. نتایج بایاس باعث می شود که ویجت تکمیل خودکار نتایج را در محدوده مشخص شده نشان دهد، اما برخی از موارد منطبق ممکن است خارج از آن منطقه باشند.

از ویژگی origin برای تعیین نقطه مبدا که از آن فاصله ژئودزیکی تا مقصد محاسبه می شود استفاده کنید. اگر این مقدار حذف شود، فاصله بر نمی گردد.

از ویژگی includedPrimaryTypes برای تعیین حداکثر پنج نوع مکان استفاده کنید. اگر هیچ نوع مشخص نشده باشد، مکان‌های همه نوع برگردانده می‌شوند.

به مرجع API مراجعه کنید

جزئیات مکان را دریافت کنید

برای برگرداندن یک شی Place از نتیجه پیش‌بینی مکان، ابتدا toPlace() فراخوانی کنید، سپس fetchFields() در شیء Place ایجاد شده فراخوانی کنید (شناسه جلسه از پیش‌بینی مکان به طور خودکار گنجانده می‌شود). فراخوانی 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;

نشانه های جلسه

نشانه‌های جلسه، مراحل پرس و جو و انتخاب یک جستجوی تکمیل خودکار کاربر را در یک جلسه مجزا برای اهداف صورت‌حساب گروه‌بندی می‌کنند. جلسه زمانی شروع می شود که کاربر شروع به تایپ کند. جلسه زمانی به پایان می رسد که کاربر مکانی را انتخاب کند و با جزئیات مکان تماس بگیرد.

برای ایجاد یک نشانه جلسه جدید و اضافه کردن آن به یک درخواست، نمونه ای از 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 یک نشانه جلسه برای جلسه بعدی ایجاد کنید.

توصیه های نشانه جلسه:

  • از نشانه‌های جلسه برای همه تماس‌های تکمیل خودکار مکان استفاده کنید.
  • برای هر جلسه یک نشانه جدید ایجاد کنید.
  • برای هر جلسه جدید یک نشانه جلسه منحصر به فرد ارسال کنید. استفاده از یک نشانه برای بیش از یک جلسه باعث می شود که هر درخواست به صورت جداگانه صورتحساب شود.

شما می توانید به صورت اختیاری نشانه تکمیل خودکار جلسه را از یک درخواست حذف کنید. اگر نشانه جلسه حذف شود، هر درخواست جداگانه صورت‌حساب می‌شود و SKU تکمیل خودکار - هر درخواست را راه‌اندازی می‌کند. اگر از یک نشانه جلسه استفاده مجدد کنید، جلسه نامعتبر تلقی می شود و درخواست ها به گونه ای محاسبه می شوند که گویی نشانه جلسه ارائه نشده است.

مثال

همانطور که کاربر یک پرس و جو را تایپ می کند، هر چند ضربه کلید (نه به ازای هر کاراکتر) یک درخواست تکمیل خودکار فراخوانی می شود و لیستی از نتایج ممکن برگردانده می شود. هنگامی که کاربر انتخابی را از لیست نتایج انجام می دهد، انتخاب به عنوان یک درخواست حساب می شود و همه درخواست های انجام شده در طول جستجو به صورت دسته بندی شده و به عنوان یک درخواست شمارش می شوند. اگر کاربر مکانی را انتخاب کند، درخواست جستجو بدون هزینه در دسترس است و فقط درخواست داده مکان هزینه می شود. اگر کاربر ظرف چند دقیقه پس از شروع جلسه انتخابی انجام ندهد، فقط درخواست جستجو شارژ می شود.

از منظر یک برنامه، جریان رویدادها به این صورت است:

  1. کاربر شروع به تایپ یک پرس و جو برای جستجوی "پاریس، فرانسه" می کند.
  2. پس از شناسایی ورودی کاربر، برنامه یک نشانه جلسه جدید، "Token A" ایجاد می کند.
  3. همانطور که کاربر تایپ می کند، API هر چند کاراکتر یک درخواست تکمیل خودکار می کند و لیست جدیدی از نتایج بالقوه را برای هر یک نمایش می دهد:
    "پ"
    "پار"
    "پاریس"
    "پاریس، فر"
  4. هنگامی که کاربر انتخاب می کند:
    • تمام درخواست های حاصل از پرس و جو گروه بندی می شوند و به عنوان یک درخواست به جلسه ارائه شده توسط "Token A" اضافه می شوند.
    • انتخاب کاربر به عنوان یک درخواست جزئیات مکان شمارش می شود و به جلسه ای که با "Token A" نشان داده می شود اضافه می شود.
  5. جلسه به پایان می رسد و برنامه "Token A" را کنار می گذارد.
درباره نحوه صدور صورتحساب جلسات اطلاعات کسب کنید

کد نمونه کامل

این بخش شامل مثال‌های کاملی است که نحوه استفاده از Place Autocomplete Data API را نشان می‌دهد.

پیش بینی های تکمیل خودکار را قرار دهید

مثال زیر فراخوانی fetchAutocompleteSuggestions() را برای ورودی "Tadi"، سپس فراخوانی toPlace() در اولین نتیجه پیش بینی و به دنبال آن فراخوانی به fetchFields() برای دریافت جزئیات مکان نشان می دهد.

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();

جاوا اسکریپت

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

Sample را امتحان کنید

تایپ تکمیل خودکار را با جلسات جلوتر قرار دهید

این مثال فراخوانی 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;

جاوا اسکریپت

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>

Sample را امتحان کنید