Yer Otomatik Tamamlama Widget'ı bir metin girişi alanı oluşturur, 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 ve bağımsız bir otomatik tamamlama kullanıcı arayüzü yerleştirmek için Yer Otomatik Tamamlama Widget'ını kullanın.
Ön koşullar
Yer Otomatik Tamamlama'yı kullanmak için Google Cloud projenizde "Places API (yeni)"yi etkinleştirmeniz gerekir. Ayrıntılar için Başlangıç başlıklı makaleyi inceleyin.
Yenilikler
Yer Adı Otomatik Tamamlama 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 (sağdan sola diller 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 kolaylaştırmak 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'ı ekleme
Otomatik Tamamlama widget'ı bir metin girişi alanı oluşturur, kullanıcı arayüzü seçim listesinde yer tahminleri sağlar ve gmp-select
dinleyicisini kullanarak kullanıcı tıklamasına yanıt olarak yer ayrıntılarını döndürür. Bu bölümde, web sayfasına veya Google Haritası'na nasıl otomatik tamamlama widget'ı ekleyeceğiniz açıklanmaktadır.
Web sayfası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. 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. 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);
Haritaya otomatik tamamlama widget'ı ekleme
Fatura adresiniz Avrupa Ekonomik Alanı (AEA) dışındaysa Google Haritalı otomatik tamamlama widget'ını da kullanabilirsiniz.
Haritaya otomatik tamamlama widget'ı eklemek için yeni bir google.maps.places.PlaceAutocompleteElement
örneği oluşturun, PlaceAutocompleteElement
öğesini div
öğesine ekleyin ve aşağıdaki örnekte gösterildiği gibi özel denetim olarak haritaya gönderin:
TypeScript
//@ts-ignore const placeAutocomplete = new google.maps.places.PlaceAutocompleteElement(); //@ts-ignore placeAutocomplete.id = 'place-autocomplete-input'; placeAutocomplete.locationBias = center; 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'; placeAutocomplete.locationBias = center; const card = document.getElementById('place-autocomplete-card'); //@ts-ignore card.appendChild(placeAutocomplete); map.controls[google.maps.ControlPosition.TOP_LEFT].push(card);
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 önyargılı hale getirerek daha alakalı tahminler sunmak için PlaceAutocompleteElementOptions'ı 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.
Herhangi bir sınır veya harita görüntü alanı sağlamazsanız API, kullanıcının konumunu IP adresinden tespit etmeye çalışır ve sonuçları bu konuma göre düzenler. Mümkün olduğunda sınır belirleyin. Aksi takdirde, farklı kullanıcılar farklı tahminler alabilir. Ayrıca, tahminleri genel olarak iyileştirmek için haritada kaydırma veya yakınlaştırma yaparak ayarladığınız bir görünüm penceresi ya da cihaz konumuna ve yarıçapa göre geliştirici tarafından ayarlanan bir görünüm penceresi gibi mantıklı bir görünüm penceresi sağlamak önemlidir. Yarıçap bilgisi yoksa Yer Otomatik Tamamlama için 5 km makul bir varsayılan değer olarak kabul edilir. Sıfır yarıçaplı (tek bir nokta), yalnızca birkaç metre genişliğinde (100 metreden az) veya tüm dünyayı kapsayan bir görüntü alanı ayarlamayın.
Yer arama özelliğini ülkeye göre kısıtlama
Yer arama işlemini bir veya daha fazla ülkeyle kısıtlamak için aşağıdaki snippet'te gösterildiği gibi ülke kodlarını belirtmek üzere includedRegionCodes
özelliğini kullanın:
const pac = new google.maps.places.PlaceAutocompleteElement({ includedRegionCodes: ['us', 'au'], });
Yer arama işlemlerini harita sınırlarıyla kısıtlama
Yer aramasını bir haritanın sınırlarıyla kısıtlamak için aşağıdaki snippet'te gösterildiği gibi sınırları eklemek üzere locationRestrictions
ö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ştiğinde güncelleyecek bir dinleyici eklediğinizden emin olun:
map.addListener('bounds_changed', () => { autocomplete.locationRestriction = map.getBounds(); });
locationRestriction
öğesini kaldırmak için null
olarak ayarlayın.
Yer arama sonuçlarında yanlılık
locationBias
özelliğini kullanarak ve burada gösterildiği gibi bir yarıçap ileterek yer arama sonuçlarını daire şeklindeki bir alana göre yönlendirin:
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 sınırlama
includedPrimaryTypes
özelliğini kullanarak ve burada gösterildiği gibi bir veya daha fazla tür belirterek yer arama sonuçlarını belirli yer türleriyle sınırlayın:
const autocomplete = new google.maps.places.PlaceAutocompleteElement({ includedPrimaryTypes: ['establishment'], });
Desteklenen türlerin tam listesi için A ve B yer türü tabloları başlıklı makaleyi inceleyin.
Yer ayrıntılarını alma
Seçilen yerle ilgili yer ayrıntılarını almak için aşağıdaki örnekte gösterildiği gibi gmp-select
öğesine PlaceAutocompleteElement
dinleyicisi ekleyin:
TypeScript
// Add the gmp-placeselect listener, and display the results. //@ts-ignore placeAutocomplete.addEventListener('gmp-select', async ({ placePrediction }) => { const place = placePrediction.toPlace(); 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-select', async ({ placePrediction }) => { const place = placePrediction.toPlace(); await place.fetchFields({ fields: ['displayName', 'formattedAddress', 'location'] }); selectedPlaceTitle.textContent = 'Selected Place:'; selectedPlaceInfo.textContent = JSON.stringify(place.toJSON(), /* replacer */ null, /* space */ 2); });
Önceki örnekte, etkinlik işleyici Place sınıfı bir nesne döndürür.
Uygulamanız için gereken Yer Ayrıntıları veri alanlarını almak üzere place.fetchFields()
numaralı telefonu arayın.
Bir sonraki örnekteki dinleyici, yer bilgisi isteğinde bulunuyor ve bu bilgiyi haritada gösteriyor.
TypeScript
// Add the gmp-placeselect listener, and display the results on the map. //@ts-ignore placeAutocomplete.addEventListener('gmp-select', async ({ placePrediction }) => { const place = placePrediction.toPlace(); 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-select', async ({ placePrediction }) => { const place = placePrediction.toPlace(); 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; });
Örnek haritalar
Bu bölümde, bu sayfada yer alan örnek haritaların tam kodu bulunmaktadır.
Otomatik tamamlama öğesi
Bu örnekte, bir web sayfasına otomatik tamamlama widget'ı eklenir ve seçilen her yerin sonuçları gösterilir.
TypeScript
async function initMap(): Promise<void> { // Request needed libraries. 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-select', async ({ placePrediction }) => { const place = placePrediction.toPlace(); 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. 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-select', async ({ placePrediction }) => { const place = placePrediction.toPlace(); 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: "AIzaSyA6myHzS10YXdcazAFalmXvDkrYCp5cLc8", v: "weekly"});</script> </body> </html>
Örneği deneyin
Otomatik tamamlama haritası
Bu örnekte, 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; let center = { lat: 40.749933, lng: -73.98633 }; // New York City 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, zoom: 13, mapId: '4504f8b37365c3d0', mapTypeControl: false, }); //@ts-ignore const placeAutocomplete = new google.maps.places.PlaceAutocompleteElement(); //@ts-ignore placeAutocomplete.id = 'place-autocomplete-input'; placeAutocomplete.locationBias = center; 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-select', async ({ placePrediction }) => { const place = placePrediction.toPlace(); 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; let center = { lat: 40.749933, lng: -73.98633 }; // New York City 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, zoom: 13, mapId: '4504f8b37365c3d0', mapTypeControl: false, }); //@ts-ignore const placeAutocomplete = new google.maps.places.PlaceAutocompleteElement(); //@ts-ignore placeAutocomplete.id = 'place-autocomplete-input'; placeAutocomplete.locationBias = center; 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-select', async ({ placePrediction }) => { const place = placePrediction.toPlace(); 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: "AIzaSyA6myHzS10YXdcazAFalmXvDkrYCp5cLc8", v: "weekly"});</script> </body> </html>
Örneği deneyin
Yer Seçici bileşenini kullanma
Yer seçici bileşeni, son kullanıcıların otomatik tamamlama özelliğini kullanarak belirli bir adres veya yer aramasını sağlayan bir metin girişidir. Bu, geliştiricilerin daha iyi haritalar ve konum özellikleri oluşturmasına yardımcı olan bir web bileşenleri grubu olan Genişletilmiş Bileşen Kitaplığı'nın bir parçasıdır.
Özel bir yer seçici bileşeni için yerleştirilebilir kod oluşturmak üzere Yer Seçici yapılandırıcısını kullanın, ardından kodu React ve Angular gibi popüler çerçevelerle veya hiç çerçeve olmadan kullanılmak üzere dışa aktarın.