Place Autocomplete Data API

Avrupa Ekonomik Alanı (AEA) geliştiricileri

Yer Otomatik Tamamlama Verileri API'si, otomatik tamamlama widget'ı ile mümkün olandan daha hassas bir kontrol derecesiyle özelleştirilmiş otomatik tamamlama deneyimleri oluşturmak için yer tahminlerini programatik olarak almanıza olanak tanır. Bu kılavuzda, kullanıcı sorgularına dayalı otomatik tamamlama istekleri yapmak için Yer Adı Otomatik Tamamlama Verileri API'sini nasıl kullanacağınızı öğreneceksiniz.

Aşağıdaki örnekte basitleştirilmiş bir otomatik tamamlama entegrasyonu gösterilmektedir. Arama sorgunuzu (ör. "pizza" veya "poke") girin, ardından istediğiniz sonucu seçmek için tıklayın.

Otomatik tamamlama istekleri

Otomatik tamamlama isteği, sorgu giriş dizesini alır ve yer tahminlerinin listesini döndürür. Otomatik tamamlama isteğinde bulunmak için fetchAutocompleteSuggestions() işlevini çağırın ve gerekli özelliklere sahip bir istek iletin. input özelliği, aranacak dizeyi içerir. Normal bir uygulamada bu değer, kullanıcı sorgu yazarken güncellenir. İstek, faturalandırma amacıyla kullanılan bir sessionToken içermelidir.

Aşağıdaki snippet'te, istek gövdesi oluşturma ve oturum jetonu ekleme, ardından PlacePrediction listesini almak için fetchAutocompleteSuggestions() işlevini çağırma gösterilmektedir.

// 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 kısıtlama

Yer Otomatik Tamamlama, varsayılan olarak kullanıcının konumuna yakın tahminler için önyargılı bir şekilde tüm yer türlerini sunar ve kullanıcının seçtiği yer için mevcut tüm veri alanlarını getirir. Sonuçları kısıtlayarak veya yönlendirerek daha alakalı tahminler sunmak için Yer Otomatik Tamamlama seçeneklerini ayarlayın.

Sonuçların kısıtlanması, otomatik tamamlama widget'ının kısıtlama alanı dışında kalan sonuçları yoksaymasına neden olur. Sonuçları harita sınırlarıyla kısıtlamak yaygın bir uygulamadır. Sonuçları önyargılı hale getirmek, otomatik tamamlama widget'ının belirtilen alan içindeki sonuçları göstermesini sağlar ancak bazı eşleşmeler bu alanın dışında olabilir.

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

En fazla beş yer türü belirtmek için includedPrimaryTypes özelliğini kullanın. Tür belirtilmezse tüm türlerdeki yerler döndürülür.

API referansına bakın

Yer ayrıntılarını alma

Bir yer tahmini sonucundan Place nesnesi döndürmek için önce toPlace() işlevini, ardından da sonuçtaki Place nesnesinde fetchFields() işlevini çağırın (yer tahmininden alınan oturum kimliği otomatik olarak eklenir). Calling fetchFields(), otomatik tamamlama oturumunu sonlandırır.

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ı, faturalandırma amacıyla kullanıcı otomatik tamamlama aramasının sorgu ve seçim aşamalarını ayrı bir oturumda gruplandırır. Kullanıcı yazmaya başladığında oturum başlar. Kullanıcı bir yer seçtiğinde ve Yer Ayrıntıları'na bir çağrı yapıldığında oturum sona erer.

Yeni bir oturum jetonu oluşturup isteğe eklemek için AutocompleteSessionToken örneği oluşturun, ardından aşağıdaki snippet'te gösterildiği gibi jetonları kullanmak üzere isteğin sessionToken özelliğini ayarlayın:

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

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

fetchFields() çağrıldığında oturum sonlandırılır. Place örneğini oluşturduktan sonra, oturum jetonunu fetchFields()'ye iletmeniz gerekmez. Bu işlem otomatik olarak yapılır.

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

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

Oturum jetonu önerileri:

  • Tüm Yer Otomatik Tamamlama çağrıları için oturum jetonlarını kullanın.
  • Her oturum için yeni bir jeton oluşturun.
  • Her yeni oturum için benzersiz bir oturum jetonu iletin. Aynı jetonun birden fazla oturumda kullanılması, her isteğin ayrı ayrı faturalandırılmasına neden olur.

İsteğe bağlı olarak, bir istekten otomatik tamamlama oturumu jetonunu çıkarabilirsiniz. Oturum jetonu atlanırsa her istek ayrı olarak faturalandırılır ve İstek Başına Otomatik Tamamlama SKU'su tetiklenir. Oturum jetonunu yeniden kullanırsanız oturum geçersiz sayılır ve istekler, oturum jetonu sağlanmamış gibi ücretlendirilir.

Örnek

Kullanıcı sorgu yazarken birkaç tuş vuruşunda bir (karakter başına değil) otomatik tamamlama isteği çağrılır ve olası sonuçların listesi döndürülür. Kullanıcı sonuç listesinden bir seçim yaptığında bu seçim istek olarak sayılır ve arama sırasında yapılan tüm istekler paketlenip tek bir istek olarak sayılır. Kullanıcı bir yer seçerse arama sorgusu ücretsiz olarak kullanılabilir ve yalnızca yer verileri isteği için ücret alınır. Kullanıcı, oturumun başlamasından sonraki birkaç dakika içinde seçim yapmazsa yalnızca arama sorgusu için ödeme alınır.

Bir uygulama açısından etkinlik akışı şu şekildedir:

  1. Bir kullanıcı, "Paris, Fransa"yı aramak için sorgu yazmaya başlıyor.
  2. Uygulama, kullanıcı girişini algıladığında yeni bir oturum jetonu ("Jeton A") oluşturur.
  3. Kullanıcı yazarken API, her birkaç karakterde bir otomatik tamamlama isteğinde bulunur ve her biri için olası sonuçların yeni bir listesini gösterir:
    "P"
    "Par"
    "Paris,"
    "Paris, Fr"
  4. Kullanıcı bir seçim yaptığında:
    • Sorgudan kaynaklanan tüm istekler gruplandırılır ve "A Jetonu" ile temsil edilen oturuma tek bir istek olarak eklenir.
    • Kullanıcının seçimi, Yer Ayrıntısı isteği olarak sayılır ve "A Jetonu" ile temsil edilen oturuma eklenir.
  5. Oturum sona erer ve uygulama "A jetonunu" atar.
Oturumların nasıl faturalandırıldığı hakkında bilgi edinin.

Eksiksiz örnek kod

Bu bölümde, Yer Adı Otomatik Tamamlama Verileri API'sinin nasıl kullanılacağını gösteren eksiksiz örnekler yer almaktadır .

Yer otomatik tamamlama tahminleri

Aşağıdaki örnekte, "Tadi" girişi için fetchAutocompleteSuggestions() çağrısı yapılması, ardından ilk tahmin sonucunda toPlace() çağrısı yapılması ve yer ayrıntılarını almak için fetchFields() çağrısı yapılması gösterilmektedir.

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

Oturumlarla yer otomatik tamamlama yazarken bulma

Bu örnekte, kullanıcı sorgularına göre fetchAutocompleteSuggestions() çağrısı yapılması, yanıt olarak tahmin edilen yerlerin listesinin gösterilmesi ve son olarak seçilen yerle ilgili yer ayrıntılarının alınması gösterilmektedir. Örnekte, kullanıcı sorgusunu nihai Yer Ayrıntıları isteğiyle gruplandırmak için oturum jetonlarının kullanımı da gösterilmektedir.

TypeScript

let titleElement;
let resultsContainerElement;
let inputElement;

let newestRequestId = 0;

// Add an initial request body.
const 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',
};

function init() {
    titleElement = document.getElementById('title');
    resultsContainerElement = document.getElementById('results');
    inputElement = document.querySelector('input');
    inputElement.addEventListener('input', makeAutocompleteRequest);
    refreshToken(request);
}

async function makeAutocompleteRequest(inputEvent) {
    // Reset elements and exit if an empty string is received.
    if (inputEvent.target.value == '') {
        titleElement.innerText = '';
        resultsContainerElement.replaceChildren();
        return;
    }

    // Add the latest char sequence to the request.
    request.input = inputEvent.target.value;

    // To avoid race conditions, store the request ID and compare after the request.
    const requestId = ++newestRequestId;

    // Fetch autocomplete suggestions and show them in a list.
    // @ts-ignore
    const { suggestions } = await google.maps.places.AutocompleteSuggestion.fetchAutocompleteSuggestions(request);

    // If the request has been superseded by a newer request, do not render the output.
    if (requestId !== newestRequestId) return;

    titleElement.innerText = `Query predictions for "${request.input}"`;

    // Clear the list first.
    resultsContainerElement.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 item element.
        const li = document.createElement('li');
        li.appendChild(a);
        resultsContainerElement.appendChild(li);
    }
}

// Event handler for clicking on a suggested place.
async function onPlaceSelected(place) {
    await place.fetchFields({
        fields: ['displayName', 'formattedAddress'],
    });
    const placeText = document.createTextNode(`${place.displayName}: ${place.formattedAddress}`);
    resultsContainerElement.replaceChildren(placeText);
    titleElement.innerText = 'Selected Place:';
    inputElement.value = '';
    refreshToken(request);
}

// Helper function to refresh the session token.
function refreshToken(request) {
    // Create a new session token and add it to the request.
    request.sessionToken = new google.maps.places.AutocompleteSessionToken();
}

declare global {
    interface Window {
      init: () => void;
    }
  }
  window.init = init;

JavaScript

let titleElement;
let resultsContainerElement;
let inputElement;
let newestRequestId = 0;
// Add an initial request body.
const 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',
};
function init() {
    titleElement = document.getElementById('title');
    resultsContainerElement = document.getElementById('results');
    inputElement = document.querySelector('input');
    inputElement.addEventListener('input', makeAutocompleteRequest);
    refreshToken(request);
}
async function makeAutocompleteRequest(inputEvent) {
    // Reset elements and exit if an empty string is received.
    if (inputEvent.target.value == '') {
        titleElement.innerText = '';
        resultsContainerElement.replaceChildren();
        return;
    }
    // Add the latest char sequence to the request.
    request.input = inputEvent.target.value;
    // To avoid race conditions, store the request ID and compare after the request.
    const requestId = ++newestRequestId;
    // Fetch autocomplete suggestions and show them in a list.
    // @ts-ignore
    const { suggestions } = await google.maps.places.AutocompleteSuggestion.fetchAutocompleteSuggestions(request);
    // If the request has been superseded by a newer request, do not render the output.
    if (requestId !== newestRequestId)
        return;
    titleElement.innerText = `Query predictions for "${request.input}"`;
    // Clear the list first.
    resultsContainerElement.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 item element.
        const li = document.createElement('li');
        li.appendChild(a);
        resultsContainerElement.appendChild(li);
    }
}
// Event handler for clicking on a suggested place.
async function onPlaceSelected(place) {
    await place.fetchFields({
        fields: ['displayName', 'formattedAddress'],
    });
    const placeText = document.createTextNode(`${place.displayName}: ${place.formattedAddress}`);
    resultsContainerElement.replaceChildren(placeText);
    titleElement.innerText = 'Selected Place:';
    inputElement.value = '';
    refreshToken(request);
}
// Helper function to refresh the session token.
function refreshToken(request) {
    // Create a new session token and add it to the request.
    request.sessionToken = new google.maps.places.AutocompleteSessionToken();
}
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=AIzaSyA6myHzS10YXdcazAFalmXvDkrYCp5cLc8&callback=init&libraries=places&v=weekly"
      defer
    ></script>
  </body>
</html>

Örneği deneyin