BasicPlaceAutocompleteElement
은 텍스트 입력란을 만들고 UI 선택 목록에 장소 예상 검색어를 제공하며 선택한 장소의 장소 ID를 반환합니다.
기본 Place Autocomplete 요소는
PlaceAutocompleteElement
보다 구현이 간단하며 다음과 같은 차이가 있습니다.
- 기본 Place Autocomplete 요소는
PlacePrediction
객체가 아닌 장소 ID만 포함하는 장소 객체를 반환합니다. 반환된 장소 ID를 Places UI Kit Details 요소와 직접 사용하여 추가 장소 세부정보를 가져올 수 있지만PlacePrediction
객체는 먼저 장소 ID로 변환해야 합니다. - 기본 Place Autocomplete 요소를 사용하면 Places API를 로드할 필요가 없습니다.
- 사용자가 장소 예상 검색어를 선택하면 기본 장소 자동 완성 요소가 입력란을 지웁니다.
기본 요건
기본 Place Autocomplete 요소를 사용하려면 Google Cloud 프로젝트에서 Places UI Kit를 사용 설정해야 합니다. 자세한 내용은 시작하기를 참고하세요.
기본 장소 자동 완성 요소 추가
이 섹션에서는 웹페이지 또는 지도에 기본 자동 완성 요소를 추가하는 방법을 보여줍니다.
웹페이지에 기본 자동 완성 요소 추가
웹페이지에 BasicAutocomplete 요소를 추가하려면 새 google.maps.places.BasicPlaceAutocompleteElement
를 만들고 다음 예와 같이 페이지에 추가합니다.
// Request needed libraries. const {BasicPlaceAutocompleteElement} = await google.maps.importLibrary('places'); // Create the input HTML element and append it. const placeAutocomplete = new BasicPlaceAutocompleteElement(); document.body.appendChild(placeAutocomplete);
지도에 기본 자동 완성 요소 추가
지도에 기본 자동 완성 요소를 추가하려면 BasicPlaceAutocompleteElement
을 gmp-map
요소에 추가하고 slot
속성을 사용하여 위치를 설정합니다. 다음 예시를 참고하세요.
<gmp-map zoom="12" center="37.4220656,-122.0840897" map-id="DEMO_MAP_ID"> <gmp-basic-place-autocomplete slot="control-inline-start-block-start"></gmp-basic-place-autocomplete> </gmp-map>
자동 완성 예상 검색어 제한
기본적으로 Basic Place Autocomplete는 사용자 위치 근처의 예상 검색어에 편중된 모든 장소 유형을 표시합니다. 결과를 제한하거나 상세 검색하여 더 관련성 높은 예상 검색어를 표시하려면
BasicPlaceAutocompleteElementOptions
를 설정하세요.
결과를 제한하면 기본 자동 완성 요소가 제한 지역 밖의 모든 결과를 무시합니다. 일반적인 방법은 결과를 지도 경계로 제한하는 것입니다. 결과를 상세 검색하면 BasicAutocomplete 요소가 지정된 지역 내 결과를 표시하지만 일부 일치 항목이 해당 지역을 벗어날 수 있습니다.
경계나 지도 표시 영역을 제공하지 않으면 API가 IP 주소에서 사용자의 위치를 감지하려고 시도하고 해당 위치에 편중된 결과를 반환합니다. 가능하면 항상 경계를 설정하세요. 그렇지 않으면 각 사용자가 받는 예측이 서로 다를 수 있습니다. 또한 일반적으로 예측을 개선하려면 지도를 화면 이동하거나 확대/축소하여 설정한 적절한 표시 영역이나 개발자가 기기 위치 및 반경을 기반으로 설정한 표시 영역을 제공해야 합니다. 반경을 사용할 수 없는 경우에는 5km가 기본 Place Autocomplete 요소에 적절한 기본값으로 간주됩니다. 반경이 0인 표시 영역(단일 점), 가로가 100m 미만에 불과한 표시 영역 또는 지구 전체 둘레에 해당하는 표시 영역은 설정하지 마세요.
국가별 장소 검색 제한
장소 검색을 하나 이상의 특정 국가로 제한하려면 다음 스니펫에 표시된 대로 includedRegionCodes
속성을 사용하여 국가 코드를 지정합니다.
const pac = new google.maps.places.BasicPlaceAutocompleteElement({ includedRegionCodes: ['us', 'au'], });
장소 검색을 지도 경계로 제한
장소 검색을 지도 경계로 제한하려면 다음 스니펫과 같이 locationRestrictions
속성을 사용하여 경계를 추가합니다.
const pac = new google.maps.places.BasicPlaceAutocompleteElement({ locationRestriction: map.getBounds(), });
지도 경계로 제한할 때는 경계가 변경될 때 경계를 업데이트하는 리스너를 추가해야 합니다.
map.addListener('bounds_changed', () => { autocomplete.locationRestriction = map.getBounds(); });
locationRestriction
을 삭제하려면 null
로 설정합니다.
장소 검색결과 상세 검색
다음과 같이 locationBias
속성을 사용하고 반경을 전달하여 장소 검색결과를 원 영역에 배치합니다.
const autocomplete = new google.maps.places.BasicPlaceAutocompleteElement({ locationBias: {radius: 100, center: {lat: 50.064192, lng: -130.605469}}, });
locationBias
를 삭제하려면 null
로 설정합니다.
장소 검색결과를 특정 유형으로 제한
다음과 같이 includedPrimaryTypes
속성을 사용하고 하나 이상의 유형을 지정하여 장소 검색 결과를 특정 유형으로 제한합니다.
const autocomplete = new google.maps.places.BasicPlaceAutocompleteElement({ includedPrimaryTypes: ['establishment'], });
지원되는 유형의 전체 목록은 장소 유형 표 A 및 B를 참고하세요.
Place Request 요소 구성
사용자가 예측을 선택할 때 Place Request 요소를 업데이트하는 리스너를 추가합니다.
// Event listener for when a place is selected from the autocomplete list. placeAutocompleteElement.addEventListener('gmp-select', (event) => { // Reset marker and InfoWindow, and prepare the details element. placeDetailsParent.appendChild(placeDetailsElement); placeDetailsElement.style.display = 'block'; advancedMarkerElement.position = null; infoWindow.close(); // Request details for the selected place. const placeDetailsRequest = placeDetailsElement.querySelector('gmp-place-details-place-request'); placeDetailsRequest.place = event.place.id; });
이 예에서는 Google 지도에 기본 자동 완성 요소를 추가하는 방법을 보여줍니다.
자바스크립트
const placeAutocompleteElement = document.querySelector('gmp-basic-place-autocomplete'); const placeDetailsElement = document.querySelector('gmp-place-details-compact'); const placeDetailsParent = placeDetailsElement.parentElement; const gmpMapElement = document.querySelector('gmp-map'); async function initMap() { // Asynchronously load required libraries from the Google Maps JS API. await google.maps.importLibrary('places'); const { AdvancedMarkerElement } = (await google.maps.importLibrary('marker')); const { InfoWindow } = (await google.maps.importLibrary('maps')); // Get the initial center directly from the gmp-map element's property. const center = gmpMapElement.center; // Set the initial location bias for the autocomplete element. placeAutocompleteElement.locationBias = center; // Update the map object with specified options. const map = gmpMapElement.innerMap; map.setOptions({ clickableIcons: false, mapTypeControl: false, streetViewControl: false, }); // Create an advanced marker to show the location of a selected place. const advancedMarkerElement = new AdvancedMarkerElement({ map: map, collisionBehavior: google.maps.CollisionBehavior.REQUIRED_AND_HIDES_OPTIONAL, }); // Create an InfoWindow to hold the place details component. const infoWindow = new InfoWindow({ minWidth: 360, disableAutoPan: true, headerDisabled: true, pixelOffset: new google.maps.Size(0, -10), }); // Event listener for when a place is selected from the autocomplete list. placeAutocompleteElement.addEventListener('gmp-select', (event) => { // Reset marker and InfoWindow, and prepare the details element. placeDetailsParent.appendChild(placeDetailsElement); placeDetailsElement.style.display = 'block'; advancedMarkerElement.position = null; infoWindow.close(); // Request details for the selected place. const placeDetailsRequest = placeDetailsElement.querySelector('gmp-place-details-place-request'); placeDetailsRequest.place = event.place.id; }); // Event listener for when the place details have finished loading. placeDetailsElement.addEventListener('gmp-load', () => { const location = placeDetailsElement.place.location; // Position the marker and open the InfoWindow at the place's location. advancedMarkerElement.position = location; infoWindow.setContent(placeDetailsElement); infoWindow.open({ map, anchor: advancedMarkerElement, }); map.setCenter(location); }); // Event listener to close the InfoWindow when the map is clicked. map.addListener('click', () => { infoWindow.close(); advancedMarkerElement.position = null; }); // Event listener for when the map finishes moving (panning or zooming). map.addListener('idle', () => { const newCenter = map.getCenter(); // Update the autocomplete's location bias to a 10km radius around the new map center. placeAutocompleteElement.locationBias = new google.maps.Circle({ center: { lat: newCenter.lat(), lng: newCenter.lng(), }, radius: 10000, // 10km in meters. }); }); } initMap();
CSS
html, body { height: 100%; margin: 0; padding: 0; } gmp-map { height: 100%; } gmp-basic-place-autocomplete { position: absolute; height: 30px; width: 500px; top: 10px; left: 10px; box-shadow: 4px 4px 5px 0px rgba(0, 0, 0, 0.2); color-scheme: light; border-radius: 10px; }
HTML
<html> <head> <title>Basic Place Autocomplete map</title> <link rel="stylesheet" type="text/css" href="./style.css" /> <script type="module" src="./index.js"></script> <!-- 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> </head> <body> <gmp-map zoom="12" center="37.4220656,-122.0840897" map-id="DEMO_MAP_ID"> <gmp-basic-place-autocomplete slot="control-inline-start-block-start"></gmp-basic-place-autocomplete> </gmp-map> <!-- Use inline styles to configure the Place Details Compact element because it will be placed within the info window, and info window content is inside the shadow DOM when using <gmp-map> --> <gmp-place-details-compact orientation="horizontal" style="width: 400px; display: none; border: none; padding: 0; margin: 0; background-color: transparent; color-scheme: light;"> <gmp-place-details-place-request></gmp-place-details-place-request> <gmp-place-standard-content></gmp-place-standard-content> </gmp-place-details-compact> </body> </html>