जगह के अपने-आप पूरा होने वाला डेटा एपीआई

जगह के अपने-आप पूरे होने वाले डेटा एपीआई की मदद से, जगहों के लिए सुझाव देखे जा सकते हैं प्रोग्रामेटिक रूप से, कस्टमाइज़ किए गए ऑटोकंप्लीट अनुभव को बेहतर कंट्रोल के साथ बनाने के लिए ऑटोकंप्लीट विजेट की मदद से जितना हो सके उतना बेहतर है. इस गाइड में आप यह जानेंगे कि उपयोगकर्ता के आधार पर अपने-आप पूरा होने वाले अनुरोध करने के लिए, ऑटोकंप्लीट की सुविधा वाला 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 का इस्तेमाल करें प्रॉपर्टी का इस्तेमाल करके, ज़्यादा से ज़्यादा पांच जगहों के टाइप बताए जा सकते हैं. अगर कोई प्रकार तय नहीं किया गया है, तो सभी प्रकार के स्थान दिखाए जाएंगे.

एपीआई का रेफ़रंस देखें

स्थान विवरण पाएं

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. इस इमेज में दिखाया गया है कि एक उपयोगकर्ता "Paris, France" खोजने के लिए क्वेरी टाइप करना शुरू करता है.
  2. उपयोगकर्ता के इनपुट का पता चलने पर, ऐप्लिकेशन नया सेशन बनाता है टोकन, "टोकन A".
  3. जैसे ही उपयोगकर्ता टाइप करता है, एपीआई हर कुछ के बाद एक ऑटोकंप्लीट अनुरोध करता है वर्ण, हर एक के लिए संभावित नतीजों की नई सूची दिखाते हुए:
    "प"
    अभी तक किसी भी व्यक्ति ने चेक इन नहीं किया है "पार"
    अभी तक किसी भी व्यक्ति ने चेक इन नहीं किया है "पेरिस"
    अभी तक किसी भी व्यक्ति ने चेक इन नहीं किया है "पेरिस, फ़्रांस"
    अभी तक किसी भी व्यक्ति ने चेक इन नहीं किया है
  4. जब उपयोगकर्ता कोई विकल्प चुनता है:
    • क्वेरी से मिलने वाले सभी अनुरोधों को एक साथ रखा जाता है और सेशन को एक अनुरोध के तौर पर "टोकन A" के ज़रिए दिखाया जाता है.
    • उपयोगकर्ता के चुने गए विकल्प को जगह की जानकारी के अनुरोध के तौर पर गिना जाता है और वाले सेशन पर क्लिक करें.
  5. सेशन खत्म होता है और ऐप्लिकेशन "टोकन A" को खारिज कर देता है.
सेशन की बिलिंग करने के तरीके के बारे में जानें

उदाहरण के तौर पर दिए गए कोड को पूरा करें

इस सेक्शन में, जगह के हिसाब से अपने-आप पूरे होने वाले डेटा एपीआई के इस्तेमाल का तरीका बताने वाले सभी उदाहरण शामिल हैं .

ऑटोकंप्लीट सुविधा की मदद से सुझाव दिखाना

नीचे दिए गए उदाहरण में, कॉल करने के तरीके के बारे में बताया गया है 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();

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

सीएसएस

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

सैंपल आज़माएं

सेशन के साथ ऑटोकंप्लीट की सुविधा को आगे रखें

इस उदाहरण में, कॉल करने के बारे में बताया गया है fetchAutocompleteSuggestions() उपयोगकर्ता की क्वेरी के हिसाब से, जवाब के तौर पर अनुमानित जगहों की सूची दिखाता है, और आखिर में जानकारी हासिल करता है चयनित स्थान के लिए स्थान विवरण. इस उदाहरण में, सेशन टोकन के इस्तेमाल के बारे में बताया गया है. जगह की जानकारी के आखिरी अनुरोध के साथ किसी उपयोगकर्ता की क्वेरी का ग्रुप बनाएं.

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;

सीएसएस

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

सैंपल आज़माएं