Yer Otomatik Tamamlama Veri API'sı

Place Autocomplete Data API, yer tahminlerini getirmenizi sağlar. daha hassas kontrol düzeyiyle özelleştirilmiş otomatik tamamlama deneyimleri oluşturmak için programatik olarak çok daha fazlasını yaptık. Bu kılavuzda, Kullanıcıya dayalı otomatik tamamlama isteklerinde bulunmak için Autocomplete Data API'yi yerleştirin daha fazla bilgi edineceksiniz.

Aşağıdaki örnekte basit bir type-ahead entegrasyonu gösterilmektedir. Arama sorgunuzu girin ve tıklayın.

Otomatik tamamlama istekleri

Otomatik tamamlama isteği, bir sorgu giriş dizesini alır ve yer tahminlerinin listesini döndürür. Alıcı: otomatik tamamlama isteğinde bulunmak için fetchAutocompleteSuggestions() numaralı telefonu arayın ve gerekli özelliklerle bir istek iletin. input özelliği, aranacak dizeyi içerir; normal bir uygulamada bu değer şu şekilde güncellenir: kullanıcı bir sorgu girer. İstek bir sessionToken içermelidir, Bu veriler, faturalandırma amacıyla kullanılır.

Aşağıdaki snippet'te istek gövdesi oluşturmayı ve oturum jetonu eklemeyi, ardından Şu öğelerin listesini almak için fetchAutocompleteSuggestions(): PlacePredictions.

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

Otomatik Tamamlama tahminlerini sınırla

Varsayılan olarak, Otomatik Yer Tamamlama özelliği, kullanıcının bulunduğu yerin yakınındaki tahminlere göre ağırlık vererek tüm yer türlerini sunar konum sağlar ve kullanıcının seçtiği yer için mevcut tüm veri alanlarını getirir. Yeri Ayarla Sonuçları kısıtlayarak veya onlara ağırlık vererek daha alakalı tahminler sunmak için otomatik tamamlama seçenekleri.

Sonuçları kısıtlamak, Otomatik Tamamlama widget'ının kısıtlama bulunduğu alan anlamına gelir. Sonuçları harita sınırlarıyla sınırlamak yaygın bir uygulamadır. Sonuçlara ağırlık verme Otomatik Tamamlama widget'ının belirtilen alandaki sonuçları göstermesini sağlar, ancak bazı eşleşmeler anlamına gelir.

Hesaplanacak başlangıç noktasını belirtmek için origin özelliğini kullanın hedefe olan jeodezik mesafedir. Bu değer atlanırsa mesafe döndürülmez.

includedPrimaryTypes'ı kullanma özelliğini kullanarak beş adede kadar yer türü belirtebilirsiniz. Herhangi bir tür belirtilmezse her tür yer döndürülür.

API referansını inceleyin

Yer ayrıntılarını al

Place içeriğini iade etmek için bir yer tahmini sonucundan nesne, ilk çağrı toPlace(), ardından fetchFields() numaralı telefonu arayın oluşturulan Place nesnesinde (yer tahminindeki oturum kimliği otomatik olarak eklenir). fetchFields() adlı kişiye çağrı şu şekilde sona erer: otomatik tamamlama oturumundan bahsedeceğiz.

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;

Oturum jetonları

Oturum jetonları, bir kullanıcı otomatik tamamlama aramasının sorgu ve seçim aşamalarını ayrı ayrı oturum açmanız gerekebilir. Oturum, kullanıcı yazmaya başladığında başlar. Kullanıcı bir yer seçtiğinde ve Yer Ayrıntılarına çağrı yapıldığında oturum sona erer.

Yeni bir oturum jetonu oluşturmak ve bunu bir isteğe eklemek için AutocompleteSessionToken ardından sessionToken ayarını yapın özelliğini kullanın:

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

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

fetchFields() olduğunda oturum sona erer. çağrılır. Place örneğini oluşturduktan sonra oturumu geçmeniz gerekmez otomatik olarak işlendiği için jetonu fetchFields() adresine gönderin.

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

Yeni bir AutocompleteSessionToken örneği oluşturarak bir sonraki oturum için oturum jetonu oluşturun.

Oturum jetonu önerileri:

  • Tüm Otomatik Yer Tamamlama çağrıları için oturum jetonları kullanın.
  • Her oturum için yeni bir jeton oluşturun.
  • Her yeni oturum için benzersiz bir oturum jetonu iletin. Birden fazla oturum için aynı jetonu kullanma her istek ayrı olarak faturalandırılır.

İsterseniz otomatik tamamlama oturum jetonunu isteğe çıkarabilirsiniz. Oturum jetonu her istek ayrı olarak faturalandırılır ve Otomatik Tamamlama - İstek Başına SKU. Bir oturum jetonunu yeniden kullanırsanız oturum geçersiz sayılır ve istekler için ücret alınır sanki hiçbir oturum jetonu sağlanmamış gibi.

Örnek

Kullanıcı bir sorgu yazarken, birkaç dakikada bir otomatik tamamlama isteği çağrılır tuşuna basarsanız (karakter başına değil) ve olası sonuçların bir listesi döndürülür. Kullanıcı sonuç listesinden seçim yaptığında, yapılan seçim arama sırasında gönderilen tüm istekler paket hâline getirilir ve sayılacaktır. Kullanıcı bir yer seçerse, arama sorgusu ücretsiz olarak sunulur ve yalnızca Yer verileri isteği için ücret alınır. Kullanıcı bir başladıktan sonra birkaç dakika içinde seçim yapabilir; ücret alınır.

Uygulamalar açısından etkinlik akışı şu şekildedir:

  1. Bir kullanıcı "Paris, Fransa"yı aramak için bir sorgu yazmaya başlıyor.
  2. Kullanıcı girişi algılandığında uygulama yeni bir oturum oluşturur "A Jetonu"nu kullanın.
  3. Kullanıcı yazarken API, birkaç dakikada bir otomatik tamamlama isteği gönderir (her biri için potansiyel sonuçların yeni bir listesini gösterir):
    "P"
    . "Par"
    . "Paris,"
    . "Paris, Cumhuriyet"
    .
  4. Kullanıcı bir seçim yaptığında:
    • Sorgudan kaynaklanan tüm istekler gruplandırılır ve oturumu "A" jetonuyla temsil edilir.
    • Kullanıcının seçimi Yer Ayrıntısı isteği olarak sayılır ve eklenir "A Jetonu" ile temsil edilen oturuma atanır.
  5. Oturum sona erer ve uygulama "A Jetonu"nu siler.
ziyaret edin. Oturumların nasıl faturalandırıldığı hakkında bilgi edinin.

Örnek kodu tamamlayın

Bu bölümde Yer Otomatik Tamamlama Veri API'sının nasıl kullanılacağını gösteren tam örnekler bulunmaktadır .

Otomatik tamamlama tahminleri yerleştirme

Aşağıdaki örnekte, fetchAutocompleteSuggestions() "Tadi" girişi için arama yapılıyor ve ardından toPlace() aranıyor ve ardından yerin ayrıntılarını almak için fetchFields() araması yapılır.

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>

Örneği Deneyin

Otomatik tamamlama türünde, oturumlarla birlikte yazımı ileri yerleştir

Bu örnekte, fetchAutocompleteSuggestions() cevap olarak tahmin edilen yerlerin bir listesini gösterme ve son olarak, seçilen yerin yer ayrıntılarına inmeniz gerekir. Örnekte, oturum jetonlarının aşağıdaki işlemler için kullanılması da gösterilmektedir: bir kullanıcı sorgusunu son Yer Ayrıntıları isteğiyle gruplandırmaktır.

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>

Örneği Deneyin