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

'जगह के ऑटोकंप्लीट' डेटा एपीआई की मदद से, प्रोग्राम के ज़रिए जगह के अनुमान मिल सकते हैं. इससे ऑटोकंप्लीट विजेट की मदद से, अपने-आप पूरा होने वाले अनुभव को ज़्यादा बेहतर तरीके से कस्टमाइज़ किया जा सकता है. इस गाइड में, आपको यह पता चलेगा कि उपयोगकर्ता की क्वेरी के आधार पर ऑटोकंप्लीट अनुरोध करने के लिए, 'प्लेस ऑटोकंप्लीट डेटा' एपीआई का इस्तेमाल कैसे किया जाता है.

यहां दिए गए उदाहरण में, टाइप-अराउंड का आसान इंटिग्रेशन दिखाया गया है. अपनी खोज क्वेरी डालें, फिर अपने पसंद के नतीजे को चुनने के लिए क्लिक करें.

ऑटोकंप्लीट करने के अनुरोध

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

उदाहरण कोड को पूरा करें

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

अपने-आप पूरा होने वाले सुझाव दिखाएं

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

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

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