Otomatik Yer Tamamlama Widget'ı bir metin giriş alanı oluşturur, kullanıcı arayüzü seçim listesinde yer tahminleri sağlar ve karar vermektir. Tamamlanan bir yeri yerleştirmek için Yer Otomatik Tamamlama Widget'ını kullanın. kullanıcı arayüzünden bağımsız olarak otomatik olarak tamamlayabilirsiniz.
Ön koşullar
Otomatik Yer Tamamlama (Önizleme) özelliğini kullanmak için "Places API"yi etkinleştirmeniz gerekir Google Cloud'unuzda
ve önyükleme yükleyicinizde beta kanalını (v: "beta"
) belirtin. Görüntüleyin
Ayrıntılar için başlayı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.
- Ekran okuyucular ve klavye etkileşimi desteği de dahil olmak üzere gelişmiş erişilebilirlik.
- Otomatik Tamamlama widget'ı yeni Yer sınıfı'nı döndürür basit bir şekilde çalışı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ı, tedarikler kullanıcı arayüzü seçim listesine tahminler yerleştirir ve yer ayrıntıları
gmp-placeselect
işleyicisi aracılığıyla bir kullanıcı tıklamasına yanıt vermek için kullanılır. Bu bölümde,
bir web sayfasına veya Google haritasına otomatik tamamlama widget'ı nasıl eklenir?
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 widget'ı şuraya ekleyin:
sayfa aşağıdaki örnekte gösterildiği gibidir:
TypeScript
// Request needed libraries. //@ts-ignore await google.maps.importLibrary("places") as google.maps.PlacesLibrary; // 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 await 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, şunu ekleyin:
PlaceAutocompleteElement
öğesini bir div
olarak ayarlamak ve haritaya özel olarak aktarmak için
kontrolü için aşağıdaki örnekte gösterildiği gibi:
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
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 getirilmiştir. 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.
Yer aramayı ülkeye göre kısıtlama
Yer aramayı bir veya daha fazla belirli ülkeyle kısıtlamak için componentRestrictions
kullanın
mülkü için ülke kodlarını aşağıdaki kodda gösterildiği gibi belirtin:
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 sınırlamak için locationRestrictions
özelliğini kullanın
özelliğini kullanın:
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ı
locationBias
özelliğini kullanarak arama sonuçlarını dairesel bir alana yerleştirme ve
aşağıdaki gibi belirli bir yarıçapı geçirme:
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
types
kullanarak yer arama sonuçlarını belirli yer türleriyle sınırlandırın
özelliğini kullanabilir ve burada gösterildiği gibi bir veya daha fazla tür belirtebilirsiniz:
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 bir gmp-place-select
dinleyicisi ekleyin:
PlaceAutocompleteElement
, aşağıdaki örnekte gösterildiği gibi:
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.
Yer Ayrıntıları veri alanlarını almak için place.fetchFields()
numaralı telefonu arayın
gerekli olduğunu unutmayı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 yere ait coğrafi kodlama sonuçlarını almak için google.maps.Geocoder
işlevini kullanarak
konumu, aşağıdaki snippet'te gösterildiği gibi:
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 her bir öğeyle ilgili sonuçları gösterir seçili yer.
TypeScript
async function initMap(): Promise<void> { // Request needed libraries. //@ts-ignore await google.maps.importLibrary("places") as google.maps.PlacesLibrary; // 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 await 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> <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> <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. Bkz. Destek için README geri bildirim almaktır.
Yer seçici bileşeni, son kullanıcıların bir belirli bir adres veya yer seçin. Genişletilmiş Bileşen Kitaplığı'nın bir parçasıdır. geliştiricilerin daha iyi haritaları ve konum özelliklerini daha hızlı oluşturmasına yardımcı olan bir dizi web bileşeni.
Yer Seçici yapılandırıcısı
Yapılandırıcıyı kullanarak özel bir Yer Seçici bileşeni için yerleştirilebilir kod oluşturun ve daha sonra React ve Angular gibi popüler çerçevelerle kullanılmasını veya hiç çerçeve olmadan kullanılmasını sağlayabilir.
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 olarak listeleniyor @googlemaps/extended-component-library. 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.
<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. Örnek kodda kullanılan bileşenleri görmek için şuna göz atın: examples sayfasını ziyaret edin.