Yer Otomatik Tamamlama Widget'ı (Önizleme)

Otomatik Yer Tamamlama Widget'ı bir metin giriş alanı oluşturur, bir kullanıcı arayüzü seçim listesinde yer tahminleri sağlar ve kullanıcının seçimine yanıt olarak yer ayrıntılarını döndürür. Web sayfanıza eksiksiz bir bağımsız otomatik tamamlama kullanıcı arayüzü yerleştirmek için Yer Otomatik Tamamlama Widget'ını kullanın.

Ön koşullar

Otomatik Yer Tamamlama (Önizleme) özelliğini kullanmak için Google Cloud projenizde "Places API"yi etkinleştirmeniz ve önyükleme yükleyicinizde beta kanalını (v: "beta") belirtmeniz gerekir. Ayrıntılar için Başlarken bölümüne bakın.

Yenilikler

Otomatik Yer Tamamlama (Önizleme) aşağıdaki şekillerde iyileştirildi:

  • Otomatik tamamlama widget'ı kullanıcı arayüzü, metin girişi yer tutucusu, tahmin listesi logosu ve yer tahminleri için bölgesel yerelleştirmeyi (RTL dilleri dahil) destekler.
  • Ekran okuyucular ve klavye etkileşimi desteği de dahil olmak üzere gelişmiş erişilebilirlik.
  • Otomatik Tamamlama widget'ı, döndürülen nesnenin işlenmesini basitleştirmek için yeni Yer sınıfını döndürür.
  • Mobil cihazlar ve küçük ekranlar için daha iyi destek.
  • Daha iyi performans ve iyileştirilmiş grafik görünüm.

Otomatik tamamlama widget'ı ekleyin

Bir web sayfasına veya Google haritasına Otomatik Tamamlama widget'ı ekleyebilirsiniz. Otomatik Tamamlama widget'ı bir metin giriş alanı oluşturur, kullanıcı arayüzü seçim listesinde yer tahminleri sağlar ve gmp-placeselect işleyicisi aracılığıyla yapılan bir kullanıcı tıklamasına yanıt olarak yer ayrıntılarını döndürür. Bu bölümde, bir web sayfasına veya Google haritasına otomatik tamamlama widget'ının nasıl ekleneceği gösterilmektedir.

Web sayfalarına Otomatik Tamamlama widget'ı ekleme

Otomatik Tamamlama widget'ını bir web sayfasına eklemek için yeni bir google.maps.places.PlaceAutocompleteElement oluşturun ve aşağıdaki örnekte gösterildiği gibi sayfaya ekleyin:

TypeScript

// Request needed libraries.
//@ts-ignore
const [{ Map }] = await Promise.all([
    google.maps.importLibrary("places"),
]);
// Create the input HTML element, and append it.
//@ts-ignore
const placeAutocomplete = new google.maps.places.PlaceAutocompleteElement();
//@ts-ignore
document.body.appendChild(placeAutocomplete);

JavaScript

// Request needed libraries.
//@ts-ignore
const [{ Map }] = await Promise.all([google.maps.importLibrary("places")]);
// Create the input HTML element, and append it.
//@ts-ignore
const placeAutocomplete = new google.maps.places.PlaceAutocompleteElement();

//@ts-ignore
document.body.appendChild(placeAutocomplete);

Kod örneğinin tamamını inceleyin.

Bir haritaya Otomatik Tamamlama widget'ı ekleme

Bir haritaya Otomatik Tamamlama widget'ı eklemek için yeni bir google.maps.places.PlaceAutocompleteElement örneği oluşturun, PlaceAutocompleteElement öğesini bir div öğesine ekleyin ve aşağıdaki örnekte gösterildiği gibi özel bir denetim olarak haritaya aktarın:

TypeScript

//@ts-ignore
const placeAutocomplete = new google.maps.places.PlaceAutocompleteElement();
//@ts-ignore
placeAutocomplete.id = 'place-autocomplete-input';

const card = document.getElementById('place-autocomplete-card') as HTMLElement;
//@ts-ignore
card.appendChild(placeAutocomplete);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(card);

JavaScript

//@ts-ignore
const placeAutocomplete = new google.maps.places.PlaceAutocompleteElement();

//@ts-ignore
placeAutocomplete.id = "place-autocomplete-input";

const card = document.getElementById("place-autocomplete-card");

//@ts-ignore
card.appendChild(placeAutocomplete);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(card);

Kod örneğinin tamamını inceleyin.

Otomatik Tamamlama tahminlerini sınırla

Otomatik Yer Tamamlama özelliği, varsayılan olarak kullanıcının konumuna yakın tahminlere göre tüm yer türlerini sunar ve kullanıcının seçtiği yere ait tüm kullanılabilir veri alanlarını getirir. Sonuçları kısıtlayarak veya onlara ağırlık vererek daha alakalı tahminler sunmak için Yer Otomatik Tamamlama seçeneklerini ayarlayın.

Sonuçları kısıtlamak, Otomatik Tamamlama widget'ının kısıtlama alanının dışındaki sonuçları yoksaymasına neden olur. 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 bu alanın dışında olabilir.

Yer aramayı ülkeye göre kısıtlama

Yer aramayı bir veya daha fazla belirli ülkeyle kısıtlamak için ülke kodlarını aşağıdaki snippet'te gösterildiği gibi belirtmek üzere componentRestrictions özelliğini kullanın:

const pac = new google.maps.places.PlaceAutocompleteElement({
  componentRestrictions: {country: ['us', 'au']},
});

Yer aramayı harita sınırlarıyla sınırla

Yer aramayı bir haritanın sınırlarıyla kısıtlamak için sınırları eklemek üzere locationRestrictions özelliğini kullanın (aşağıdaki snippet'te gösterildiği gibi):

const pac = new google.maps.places.PlaceAutocompleteElement({
  locationRestriction: map.getBounds(),
});

Harita sınırlarıyla kısıtlama yaparken sınırları değiştiklerinde güncellemek için bir işleyici eklediğinizden emin olun:

map.addListener('bounds_changed', () => {
  autocomplete.locationRestriction = map.getBounds();
});

locationRestriction öğesini kaldırmak için null olarak ayarlayın.

Taraflı yer arama sonuçları

Burada gösterildiği gibi, locationBias özelliğini kullanarak ve bir yarıçap değeri ileterek arama sonuçlarını dairesel bir alana çevirebilirsiniz:

const autocomplete = new google.maps.places.PlaceAutocompleteElement({
  locationBias: {radius: 100, center: {lat: 50.064192, lng: -130.605469}},
});

locationBias öğesini kaldırmak için null olarak ayarlayın.

Yer arama sonuçlarını belirli türlerle kısıtlama

Aşağıda gösterildiği gibi, types özelliğini kullanarak ve bir veya daha fazla tür belirterek yer arama sonuçlarını belirli yer türleriyle sınırlandırabilirsiniz:

const autocomplete = new google.maps.places.PlaceAutocompleteElement({
  types: ['establishment'],
});

Desteklenen türlerin tam listesi için Tablo 3: Yer otomatik tamamlama isteklerinde desteklenen türler bölümüne bakın.

Yer ayrıntılarını al

Seçili yerin yer ayrıntılarını almak için aşağıdaki örnekte gösterildiği gibi PlaceAutocompleteElement öğesine bir gmp-place-select işleyicisi ekleyin:

TypeScript

// Add the gmp-placeselect listener, and display the results.
//@ts-ignore
placeAutocomplete.addEventListener('gmp-placeselect', async ({ place }) => {
    await place.fetchFields({ fields: ['displayName', 'formattedAddress', 'location'] });

    selectedPlaceTitle.textContent = 'Selected Place:';
    selectedPlaceInfo.textContent = JSON.stringify(
        place.toJSON(), /* replacer */ null, /* space */ 2);
});

JavaScript

// Add the gmp-placeselect listener, and display the results.
//@ts-ignore
placeAutocomplete.addEventListener("gmp-placeselect", async ({ place }) => {
  await place.fetchFields({
    fields: ["displayName", "formattedAddress", "location"],
  });
  selectedPlaceTitle.textContent = "Selected Place:";
  selectedPlaceInfo.textContent = JSON.stringify(
    place.toJSON(),
    /* replacer */ null,
    /* space */ 2,
  );
});

Kod örneğinin tamamını inceleyin.

Yukarıdaki örnekte, etkinlik işleyici Yer sınıfı nesnesini döndürür. Başvurunuz için gereken Yer Ayrıntıları veri alanlarını almak üzere place.fetchFields() numaralı telefonu arayın.

Bir sonraki örnekte verilen işleyici, yer bilgilerini ister ve harita üzerinde gösterir.

TypeScript

// Add the gmp-placeselect listener, and display the results on the map.
//@ts-ignore
placeAutocomplete.addEventListener('gmp-placeselect', async ({ place }) => {
    await place.fetchFields({ fields: ['displayName', 'formattedAddress', 'location'] });

    // If the place has a geometry, then present it on a map.
    if (place.viewport) {
        map.fitBounds(place.viewport);
    } else {
        map.setCenter(place.location);
        map.setZoom(17);
    }

    let content = '<div id="infowindow-content">' +
    '<span id="place-displayname" class="title">' + place.displayName + '</span><br />' +
    '<span id="place-address">' + place.formattedAddress + '</span>' +
    '</div>';

    updateInfoWindow(content, place.location);
    marker.position = place.location;
});

JavaScript

// Add the gmp-placeselect listener, and display the results on the map.
//@ts-ignore
placeAutocomplete.addEventListener("gmp-placeselect", async ({ place }) => {
  await place.fetchFields({
    fields: ["displayName", "formattedAddress", "location"],
  });
  // If the place has a geometry, then present it on a map.
  if (place.viewport) {
    map.fitBounds(place.viewport);
  } else {
    map.setCenter(place.location);
    map.setZoom(17);
  }

  let content =
    '<div id="infowindow-content">' +
    '<span id="place-displayname" class="title">' +
    place.displayName +
    "</span><br />" +
    '<span id="place-address">' +
    place.formattedAddress +
    "</span>" +
    "</div>";

  updateInfoWindow(content, place.location);
  marker.position = place.location;
});

Kod örneğinin tamamını inceleyin.

Seçili yer için coğrafi kodlama sonuçlarını alın

Seçili yer için coğrafi kodlama sonuçlarını almak amacıyla, aşağıdaki snippet'te gösterildiği şekilde konumu almak için google.maps.Geocoder kullanın:

const map = new google.maps.Map(document.getElementById('map'), {
  center: {lat: 50.064192, lng: -130.605469},
  zoom: 3,
});

const marker = new google.maps.Marker({map});
const autocomplete = new google.maps.places.PlaceAutocompleteElement();
const geocoder = new google.maps.Geocoder();

autocomplete.addListener('gmp-placeselect', async ({prediction: place}) => {
  const results = await geocoder.geocode({place.id});
  marker.setPlace({
    placeId: place.id,
    location: results[0].geometry.location,
  });
});

Örnek haritalar

Bu bölümde, bu sayfada gösterilen örnek haritalara ait kodun tamamı yer almaktadır.

Otomatik tamamlama öğesi

Bu örnek, web sayfasına bir Otomatik Tamamlama widget'ı ekler ve seçilen her yer için sonuçları gösterir.

TypeScript

async function initMap(): Promise<void> {
    // Request needed libraries.
    //@ts-ignore
    const [{ Map }] = await Promise.all([
        google.maps.importLibrary("places"),
    ]);
    // Create the input HTML element, and append it.
    //@ts-ignore
    const placeAutocomplete = new google.maps.places.PlaceAutocompleteElement();
    //@ts-ignore
    document.body.appendChild(placeAutocomplete);

    // Inject HTML UI.
    const selectedPlaceTitle = document.createElement('p');
    selectedPlaceTitle.textContent = '';
    document.body.appendChild(selectedPlaceTitle);

    const selectedPlaceInfo = document.createElement('pre');
    selectedPlaceInfo.textContent = '';
    document.body.appendChild(selectedPlaceInfo);

    // Add the gmp-placeselect listener, and display the results.
    //@ts-ignore
    placeAutocomplete.addEventListener('gmp-placeselect', async ({ place }) => {
        await place.fetchFields({ fields: ['displayName', 'formattedAddress', 'location'] });

        selectedPlaceTitle.textContent = 'Selected Place:';
        selectedPlaceInfo.textContent = JSON.stringify(
            place.toJSON(), /* replacer */ null, /* space */ 2);
    });
}

initMap();

JavaScript

async function initMap() {
  // Request needed libraries.
  //@ts-ignore
  const [{ Map }] = await Promise.all([google.maps.importLibrary("places")]);
  // Create the input HTML element, and append it.
  //@ts-ignore
  const placeAutocomplete = new google.maps.places.PlaceAutocompleteElement();

  //@ts-ignore
  document.body.appendChild(placeAutocomplete);

  // Inject HTML UI.
  const selectedPlaceTitle = document.createElement("p");

  selectedPlaceTitle.textContent = "";
  document.body.appendChild(selectedPlaceTitle);

  const selectedPlaceInfo = document.createElement("pre");

  selectedPlaceInfo.textContent = "";
  document.body.appendChild(selectedPlaceInfo);
  // Add the gmp-placeselect listener, and display the results.
  //@ts-ignore
  placeAutocomplete.addEventListener("gmp-placeselect", async ({ place }) => {
    await place.fetchFields({
      fields: ["displayName", "formattedAddress", "location"],
    });
    selectedPlaceTitle.textContent = "Selected Place:";
    selectedPlaceInfo.textContent = JSON.stringify(
      place.toJSON(),
      /* replacer */ null,
      /* space */ 2,
    );
  });
}

initMap();

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

p {
  font-family: Roboto, sans-serif;
  font-weight: bold;
}

HTML

<html>
  <head>
    <title>Place Autocomplete element</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>
    <p style="font-family: roboto, sans-serif">Search for a place here:</p>

    <!-- 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: "beta"});</script>
  </body>
</html>

Örneği Deneyin

Haritayı otomatik tamamla

Bu örnekte, bir Google haritasına Otomatik Tamamlama widget'ının nasıl ekleneceği gösterilmektedir.

TypeScript

let map: google.maps.Map;
let marker: google.maps.marker.AdvancedMarkerElement;
let infoWindow: google.maps.InfoWindow;
async function initMap(): Promise<void> {
    // Request needed libraries.
    //@ts-ignore
    const [{ Map }, { AdvancedMarkerElement }] = await Promise.all([
        google.maps.importLibrary("marker"),
        google.maps.importLibrary("places")
      ]);

    // Initialize the map.
    map = new google.maps.Map(document.getElementById('map') as HTMLElement, {
        center: { lat: 40.749933, lng: -73.98633 },
        zoom: 13,
        mapId: '4504f8b37365c3d0',
        mapTypeControl: false,
    });
    //@ts-ignore
    const placeAutocomplete = new google.maps.places.PlaceAutocompleteElement();
    //@ts-ignore
    placeAutocomplete.id = 'place-autocomplete-input';

    const card = document.getElementById('place-autocomplete-card') as HTMLElement;
    //@ts-ignore
    card.appendChild(placeAutocomplete);
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(card);

    // Create the marker and infowindow
    marker = new google.maps.marker.AdvancedMarkerElement({
        map,
    });

    infoWindow = new google.maps.InfoWindow({});

    // Add the gmp-placeselect listener, and display the results on the map.
    //@ts-ignore
    placeAutocomplete.addEventListener('gmp-placeselect', async ({ place }) => {
        await place.fetchFields({ fields: ['displayName', 'formattedAddress', 'location'] });

        // If the place has a geometry, then present it on a map.
        if (place.viewport) {
            map.fitBounds(place.viewport);
        } else {
            map.setCenter(place.location);
            map.setZoom(17);
        }

        let content = '<div id="infowindow-content">' +
        '<span id="place-displayname" class="title">' + place.displayName + '</span><br />' +
        '<span id="place-address">' + place.formattedAddress + '</span>' +
        '</div>';

        updateInfoWindow(content, place.location);
        marker.position = place.location;
    });
}

// Helper function to create an info window.
function updateInfoWindow(content, center) {
    infoWindow.setContent(content);
    infoWindow.setPosition(center);
    infoWindow.open({
        map,
        anchor: marker,
        shouldFocus: false,
    });
}

initMap();

JavaScript

let map;
let marker;
let infoWindow;

async function initMap() {
  // Request needed libraries.
  //@ts-ignore
  const [{ Map }, { AdvancedMarkerElement }] = await Promise.all([
    google.maps.importLibrary("marker"),
    google.maps.importLibrary("places"),
  ]);

  // Initialize the map.
  map = new google.maps.Map(document.getElementById("map"), {
    center: { lat: 40.749933, lng: -73.98633 },
    zoom: 13,
    mapId: "4504f8b37365c3d0",
    mapTypeControl: false,
  });

  //@ts-ignore
  const placeAutocomplete = new google.maps.places.PlaceAutocompleteElement();

  //@ts-ignore
  placeAutocomplete.id = "place-autocomplete-input";

  const card = document.getElementById("place-autocomplete-card");

  //@ts-ignore
  card.appendChild(placeAutocomplete);
  map.controls[google.maps.ControlPosition.TOP_LEFT].push(card);
  // Create the marker and infowindow
  marker = new google.maps.marker.AdvancedMarkerElement({
    map,
  });
  infoWindow = new google.maps.InfoWindow({});
  // Add the gmp-placeselect listener, and display the results on the map.
  //@ts-ignore
  placeAutocomplete.addEventListener("gmp-placeselect", async ({ place }) => {
    await place.fetchFields({
      fields: ["displayName", "formattedAddress", "location"],
    });
    // If the place has a geometry, then present it on a map.
    if (place.viewport) {
      map.fitBounds(place.viewport);
    } else {
      map.setCenter(place.location);
      map.setZoom(17);
    }

    let content =
      '<div id="infowindow-content">' +
      '<span id="place-displayname" class="title">' +
      place.displayName +
      "</span><br />" +
      '<span id="place-address">' +
      place.formattedAddress +
      "</span>" +
      "</div>";

    updateInfoWindow(content, place.location);
    marker.position = place.location;
  });
}

// Helper function to create an info window.
function updateInfoWindow(content, center) {
  infoWindow.setContent(content);
  infoWindow.setPosition(center);
  infoWindow.open({
    map,
    anchor: marker,
    shouldFocus: false,
  });
}

initMap();

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

#place-autocomplete-card {
  background-color: #fff;
  border-radius: 5px;
  box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px;
  margin: 10px;
  padding: 5px;
  font-family: Roboto, sans-serif;
  font-size: large;
  font-weight: bold;
}

gmp-place-autocomplete {
  width: 300px;
}

#infowindow-content .title {
  font-weight: bold;
}

#map #infowindow-content {
  display: inline;
}

HTML

<html>
  <head>
    <title>Place Autocomplete map</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 class="place-autocomplete-card" id="place-autocomplete-card">
      <p>Search for a place here:</p>
    </div>
    <div id="map"></div>

    <!-- 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: "beta"});</script>
  </body>
</html>

Örneği Deneyin

Yer Seçici bileşenini kullanma

Not: Bu örnekte açık kaynak bir kitaplık kullanılmaktadır. Kitaplıkla ilgili destek ve geri bildirim için BENİOKU sayfasını inceleyin.

Yer seçici bileşeni, son kullanıcıların otomatik tamamlama özelliğini kullanarak belirli bir adresi veya yeri aramasına olanak tanıyan bir metin girişidir. Geliştiricilerin daha iyi haritaları ve konum özelliklerini daha hızlı oluşturmasına yardımcı olan bir dizi web bileşeni olan Genişletilmiş Bileşen Kitaplığı'nın bir parçasıdır.

Yer Seçici yapılandırıcısı

Özel bir Yer Seçici bileşeni için yerleştirilebilir kod oluşturmak üzere yapılandırıcıyı kullanın, ardından React ve Angular gibi popüler çerçevelerle veya hiç çerçeve olmadan kullanmak üzere dışa aktarın.

Başlayın

Başlamak için Genişletilmiş Bileşen kitaplığını npm ile yükleyin.

En iyi performans için bir paket yöneticisi kullanın ve yalnızca ihtiyacınız olan bileşenleri içe aktarın. Bu paket, npm'de @googlemaps/extended-component-library olarak listelenir. Uygulamayı şununla yükleyin:

  npm i @googlemaps/extended-component-library;

Ardından uygulamanızda kullandığınız bileşenleri içe aktarın.

  import '@googlemaps/extended-component-library/place_picker.js';

npm kitaplığını yükledikten sonra Cloud Console'dan bir API anahtarı alın.

  <gmpx-api-loader key="YOUR_API_KEY" solution-channel="GMP_DOCS_placepicker_v1"></gmpx-api-loader>

Yer seçici bileşen etiketini kullanın.

  <gmpx-place-picker placeholder="Enter a place" id="place-picker" style="width: 100%">
  </gmpx-place-picker>

Daha fazla bilgi için GitHub veya npm'ye göz atın. Örnek kodda kullanılan bileşenleri görmek için GitHub'daki örnekler sayfasına göz atın.