Place Autocomplete Data API를 사용하면 프로그래매틱 방식으로 장소 예측을 가져와 자동 완성 위젯으로 가능한 것보다 더 세밀하게 제어되는 맞춤 자동 완성 환경을 만들 수 있습니다. 이 가이드에서는 Place Autocomplete Data API를 사용하여 사용자 쿼리를 기반으로 자동 완성 요청을 하는 방법을 알아봅니다.
다음 예는 단순화된 자동 완성 통합을 보여줍니다. '피자' 또는 '포케'와 같은 검색어를 입력한 다음 클릭하여 원하는 결과를 선택합니다.
Autocomplete 요청
자동 완성 요청은 쿼리 입력 문자열을 가져와 장소 예상 검색어 목록을 반환합니다. 자동 완성 요청을 하려면 fetchAutocompleteSuggestions()를 호출하고 필요한 속성이 있는 요청을 전달합니다. input 속성에는 검색할 문자열이 포함됩니다. 일반적인 애플리케이션에서 이 값은 사용자가 쿼리를 입력할 때 업데이트됩니다. 요청에는 결제 목적으로 사용되는 sessionToken가 포함되어야 합니다.
다음 스니펫은 요청 본문을 만들고 세션 토큰을 추가한 다음 fetchAutocompleteSuggestions()을 호출하여 PlacePrediction 목록을 가져오는 방법을 보여줍니다.
// 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;
자동 완성 예상 검색어 제한
기본적으로 Place Autocomplete는 사용자 위치 근처의 예상 검색어에 편중된 모든 장소 유형을 표시하며 사용자가 선택한 장소의 사용 가능한 모든 데이터 필드를 가져옵니다. 결과를 제한하거나 상세 검색하여 더 관련성 높은 예상 검색어를 표시하려면 Place Autocomplete 옵션을 설정하세요.
결과를 제한하면 자동 완성 위젯이 제한 지역 밖의 모든 결과를 무시합니다. 일반적인 방법은 결과를 지도 경계로 제한하는 것입니다. 결과를 상세 검색하면 자동 완성 위젯이 지정된 지역 내 결과를 표시하지만 일부 일치 항목이 해당 지역을 벗어날 수 있습니다.
origin 속성을 사용하여 목적지까지의 측지 거리를 계산할 출발점을 지정합니다. 이 값이 생략되면 거리가 반환되지 않습니다.
includedPrimaryTypes 속성을 사용하여 최대 5개의 장소 유형을 지정합니다.
유형을 지정하지 않으면 모든 유형의 장소가 반환됩니다.
장소 세부정보 가져오기
장소 예측 결과에서 Place 객체를 반환하려면 먼저 toPlace()를 호출한 다음 결과 Place 객체에서 fetchFields()를 호출합니다 (장소 예측의 세션 ID가 자동으로 포함됨). fetchFields()를 호출하면 자동 완성 세션이 종료됩니다.
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}`;
세션 토큰
세션 토큰은 사용자 자동 완성 검색의 쿼리 및 선택 단계를 결제 목적의 개별 세션으로 그룹화합니다. 세션은 사용자가 입력을 시작할 때 시작됩니다. 사용자가 장소를 선택하고 Place Details 호출이 이루어지면 세션이 종료됩니다.
새 세션 토큰을 만들어 요청에 추가하려면 AutocompleteSessionToken 인스턴스를 만든 다음 다음 스니펫과 같이 토큰을 사용하도록 요청의 sessionToken 속성을 설정합니다.
// Create a session token. const token = new AutocompleteSessionToken(); // Add the token to the request. // @ts-ignore request.sessionToken = token;
fetchFields()이 호출되면 세션이 종료됩니다. Place 인스턴스를 만든 후에는 세션 토큰을 fetchFields()에 전달할 필요가 없습니다. 자동으로 처리되기 때문입니다.
await place.fetchFields({ fields: ['displayName', 'formattedAddress'], });
AutocompleteSessionToken의 새 인스턴스를 만들어 다음 세션의 세션 토큰을 만듭니다.
세션 토큰 권장사항:
- 모든 Place Autocomplete 호출에 세션 토큰을 사용합니다.
- 각 세션에 대해 새 토큰을 생성합니다.
- 새 세션마다 고유한 세션 토큰을 전달합니다. 두 개 이상의 세션에 동일한 토큰을 사용하면 각 요청에 대해 개별적으로 요금이 청구됩니다.
원하는 경우 요청에서 자동 완성 세션 토큰을 생략할 수 있습니다. 세션 토큰이 생략되면 각 요청에 대해 별도로 요금이 청구되어 Autocomplete - Per Request SKU가 트리거됩니다. 세션 토큰을 재사용하면 세션이 유효하지 않은 것으로 간주되어 세션 토큰이 제공되지 않은 것처럼 요청에 대해 요금이 청구됩니다.
예
사용자가 쿼리를 입력하면 몇 번의 키 입력마다 (문자별이 아님) 자동 완성 요청이 호출되고 가능한 결과 목록이 반환됩니다. 사용자가 결과 목록에서 선택하면 선택이 요청으로 간주되며 검색 중에 이루어진 모든 요청이 번들로 묶여 단일 요청으로 집계됩니다. 사용자가 장소를 선택하면 검색어는 무료로 제공되며 장소 데이터 요청에만 요금이 청구됩니다. 사용자가 세션이 시작된 후 몇 분 이내에 선택하지 않으면 검색어만 청구됩니다.
앱의 관점에서 이벤트 흐름은 다음과 같습니다.
- 사용자가 '파리, 프랑스'를 검색하기 위해 검색어를 입력하기 시작합니다.
- 사용자 입력을 감지하면 앱은 새 세션 토큰 '토큰 A'를 만듭니다.
- 사용자가 입력하면 API는 몇 글자마다 자동 완성 요청을 하여 각 글자에 대한 잠재적 결과의 새 목록을 표시합니다.
'P'
'Par'
'Paris'
'Paris, Fr'
- 사용자가 선택하면 다음이 적용됩니다.
- 쿼리로 인해 발생하는 모든 요청은 그룹화되어 '토큰 A'로 표시되는 세션에 단일 요청으로 추가됩니다.
- 사용자의 선택은 Place Detail 요청으로 집계되고 '토큰 A'로 표시되는 세션에 추가됩니다.
- 세션이 종료되고 앱이 '토큰 A'를 삭제합니다.
예시 코드 작성
이 섹션에는 Place Autocomplete Data API를 사용하는 방법을 보여주는 완전한 예가 포함되어 있습니다 .장소 자동 완성 예상 검색어
다음 예에서는 'Tadi' 입력에 대해 fetchAutocompleteSuggestions()를 호출한 다음 첫 번째 예측 결과에 대해 toPlace()를 호출하고 fetchFields()를 호출하여 장소 세부정보를 가져옵니다.
TypeScript
async function init() { 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 + '":' ) ); const resultsElement = document.getElementById('results') as HTMLElement; for (let suggestion of suggestions) { const placePrediction = suggestion.placePrediction; // Create a new list element. const listItem = document.createElement('li'); 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
async function init() { 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 + '":')); const resultsElement = document.getElementById('results'); for (let suggestion of suggestions) { const placePrediction = suggestion.placePrediction; // Create a new list element. const listItem = document.createElement('li'); 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>
<!-- 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>
<div id="title"></div>
<ul id="results"></ul>
<p><span id="prediction"></span></p>
<img
class="powered-by-google"
src="./powered_by_google_on_white.png"
alt="Powered by Google" />
</body>
</html>샘플 사용해 보기
세션이 있는 Place Autocomplete 미리 입력
이 예에서는 다음 개념을 보여줍니다.
- 사용자 쿼리를 기반으로
fetchAutocompleteSuggestions()를 호출하고 예상 장소 목록을 응답으로 표시합니다. - 세션 토큰을 사용하여 사용자 쿼리를 최종 Place Details 요청과 그룹화합니다.
- 선택한 장소의 장소 세부정보를 가져오고 마커를 표시합니다.
- 제어 슬롯을 사용하여
gmp-map요소에 UI 요소를 중첩합니다.
TypeScript
const mapElement = document.querySelector('gmp-map') as google.maps.MapElement; let innerMap: google.maps.Map; let marker: google.maps.marker.AdvancedMarkerElement; let titleElement = document.querySelector('.title') as HTMLElement; let resultsContainerElement = document.querySelector('.results') as HTMLElement; let inputElement = document.querySelector('input') as HTMLInputElement; let tokenStatusElement = document.querySelector('.token-status') as HTMLElement; let newestRequestId = 0; let tokenCount = 0; // Create an initial request body. const request: google.maps.places.AutocompleteRequest = { input: '', includedPrimaryTypes: [ 'restaurant', 'cafe', 'museum', 'park', 'botanical_garden', ], }; async function init() { await google.maps.importLibrary('maps'); innerMap = mapElement.innerMap; innerMap.setOptions({ mapTypeControl: false, }); // Update request center and bounds when the map bounds change. google.maps.event.addListener(innerMap, 'bounds_changed', async () => { request.locationRestriction = innerMap.getBounds(); request.origin = innerMap.getCenter(); }); inputElement.addEventListener('input', makeAutocompleteRequest); } async function makeAutocompleteRequest(inputEvent) { // To avoid race conditions, store the request ID and compare after the request. const requestId = ++newestRequestId; const { AutocompleteSuggestion } = (await google.maps.importLibrary( 'places' )) as google.maps.PlacesLibrary; if (!inputEvent.target?.value) { titleElement.textContent = ''; resultsContainerElement.replaceChildren(); return; } // Add the latest char sequence to the request. request.input = (inputEvent.target as HTMLInputElement).value; // Fetch autocomplete suggestions and show them in a list. const { suggestions } = await AutocompleteSuggestion.fetchAutocompleteSuggestions(request); // If the request has been superseded by a newer request, do not render the output. if (requestId !== newestRequestId) return; titleElement.innerText = `Place predictions for "${request.input}"`; // Clear the list first. resultsContainerElement.replaceChildren(); for (const suggestion of suggestions) { const placePrediction = suggestion.placePrediction; if (!placePrediction) { continue; } // Create a link for the place, add an event handler to fetch the place. // We are using a button element to take advantage of its a11y capabilities. const placeButton = document.createElement('button'); placeButton.addEventListener('click', () => { onPlaceSelected(placePrediction.toPlace()); }); placeButton.textContent = placePrediction.text.toString(); placeButton.classList.add('place-button'); // Create a new list item element. const li = document.createElement('li'); li.appendChild(placeButton); resultsContainerElement.appendChild(li); } } // Event handler for clicking on a suggested place. async function onPlaceSelected(place: google.maps.places.Place) { const { AdvancedMarkerElement } = (await google.maps.importLibrary( 'marker' )) as google.maps.MarkerLibrary; await place.fetchFields({ fields: ['displayName', 'formattedAddress', 'location'], }); resultsContainerElement.textContent = `${place.displayName}: ${place.formattedAddress}`; titleElement.textContent = 'Selected Place:'; inputElement.value = ''; await refreshToken(); // Remove the previous marker, if it exists. if (marker) { marker.remove(); } // Create a new marker. marker = new AdvancedMarkerElement({ map: innerMap, position: place.location, title: place.displayName, }); // Center the map on the selected place. if (place.location) { innerMap.setCenter(place.location); innerMap.setZoom(15); } } // Helper function to refresh the session token. async function refreshToken() { const { AutocompleteSessionToken } = (await google.maps.importLibrary( 'places' )) as google.maps.PlacesLibrary; // Increment the token counter. tokenCount++; // Create a new session token and add it to the request. request.sessionToken = new AutocompleteSessionToken(); tokenStatusElement.textContent = `Session token count: ${tokenCount}`; } init();
JavaScript
const mapElement = document.querySelector('gmp-map'); let innerMap; let marker; let titleElement = document.querySelector('.title'); let resultsContainerElement = document.querySelector('.results'); let inputElement = document.querySelector('input'); let tokenStatusElement = document.querySelector('.token-status'); let newestRequestId = 0; let tokenCount = 0; // Create an initial request body. const request = { input: '', includedPrimaryTypes: [ 'restaurant', 'cafe', 'museum', 'park', 'botanical_garden', ], }; async function init() { await google.maps.importLibrary('maps'); innerMap = mapElement.innerMap; innerMap.setOptions({ mapTypeControl: false, }); // Update request center and bounds when the map bounds change. google.maps.event.addListener(innerMap, 'bounds_changed', async () => { request.locationRestriction = innerMap.getBounds(); request.origin = innerMap.getCenter(); }); inputElement.addEventListener('input', makeAutocompleteRequest); } async function makeAutocompleteRequest(inputEvent) { // To avoid race conditions, store the request ID and compare after the request. const requestId = ++newestRequestId; const { AutocompleteSuggestion } = (await google.maps.importLibrary('places')); if (!inputEvent.target?.value) { titleElement.textContent = ''; resultsContainerElement.replaceChildren(); return; } // Add the latest char sequence to the request. request.input = inputEvent.target.value; // Fetch autocomplete suggestions and show them in a list. const { suggestions } = await AutocompleteSuggestion.fetchAutocompleteSuggestions(request); // If the request has been superseded by a newer request, do not render the output. if (requestId !== newestRequestId) return; titleElement.innerText = `Place predictions for "${request.input}"`; // Clear the list first. resultsContainerElement.replaceChildren(); for (const suggestion of suggestions) { const placePrediction = suggestion.placePrediction; if (!placePrediction) { continue; } // Create a link for the place, add an event handler to fetch the place. // We are using a button element to take advantage of its a11y capabilities. const placeButton = document.createElement('button'); placeButton.addEventListener('click', () => { onPlaceSelected(placePrediction.toPlace()); }); placeButton.textContent = placePrediction.text.toString(); placeButton.classList.add('place-button'); // Create a new list item element. const li = document.createElement('li'); li.appendChild(placeButton); resultsContainerElement.appendChild(li); } } // Event handler for clicking on a suggested place. async function onPlaceSelected(place) { const { AdvancedMarkerElement } = (await google.maps.importLibrary('marker')); await place.fetchFields({ fields: ['displayName', 'formattedAddress', 'location'], }); resultsContainerElement.textContent = `${place.displayName}: ${place.formattedAddress}`; titleElement.textContent = 'Selected Place:'; inputElement.value = ''; await refreshToken(); // Remove the previous marker, if it exists. if (marker) { marker.remove(); } // Create a new marker. marker = new AdvancedMarkerElement({ map: innerMap, position: place.location, title: place.displayName, }); // Center the map on the selected place. if (place.location) { innerMap.setCenter(place.location); innerMap.setZoom(15); } } // Helper function to refresh the session token. async function refreshToken() { const { AutocompleteSessionToken } = (await google.maps.importLibrary('places')); // Increment the token counter. tokenCount++; // Create a new session token and add it to the request. request.sessionToken = new AutocompleteSessionToken(); tokenStatusElement.textContent = `Session token count: ${tokenCount}`; } init();
CSS
/* * Always set the map height explicitly to define the size of the div element * that contains the map. */ gmp-map { height: 100%; } /* * Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; } .place-button { height: 3rem; width: 100%; background-color: transparent; text-align: left; border: none; cursor: pointer; } .place-button:focus-visible { outline: 2px solid #0056b3; border-radius: 2px; } .input { width: 300px; font-size: small; margin-bottom: 1rem; } /* Styles for the floating panel */ .controls { background-color: #fff; border-radius: 8px; box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3); font-family: sans-serif; font-size: small; margin: 12px; padding: 1rem; } .title { font-weight: bold; margin-top: 1rem; margin-bottom: 0.5rem; } .results { list-style-type: none; margin: 0; padding: 0; } .results li:not(:last-child) { border-bottom: 1px solid #ddd; } .results li:hover { background-color: #eee; }
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>
<!-- 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 center="37.7893, -122.4039" zoom="12" map-id="DEMO_MAP_ID">
<div class="controls" slot="control-inline-start-block-start">
<input
type="text"
class="input"
placeholder="Search for a place..."
autocomplete="off" /><!-- Turn off the input's own autocomplete (not supported by all browsers).-->
<div class="token-status"></div>
<div class="title"></div>
<ol class="results"></ol>
</div>
</gmp-map>
</body>
</html>샘플 사용해 보기
Autocomplete (신규) 최적화
이 섹션에서는 Autocomplete (New) 서비스를 최대한 활용하는 데 도움이 되는 권장사항을 설명합니다.
다음은 일반 가이드라인입니다.
- 작동하는 사용자 인터페이스를 개발하는 가장 빠른 방법은 Maps JavaScript API 자동 완성 (신규) 위젯, Android용 Places SDK 자동 완성 (신규) 위젯, iOS용 Places SDK 자동 완성 (신규) 위젯을 사용하는 것입니다.
- 처음부터 필수 Autocomplete (New) 데이터 필드를 이해합니다.
- 위치 상세 검색 및 위치 제한 필드는 선택사항이지만 자동 완성 성능에 상당한 영향을 미칠 수 있습니다.
- API가 오류를 반환하는 경우 오류 처리를 사용하여 앱의 성능이 적절히 저하되도록 합니다.
- 선택된 항목이 없을 때 앱에서 처리하고 사용자에게 계속할 수 있는 방법을 제공하도록 합니다.
비용 최적화 권장사항
기본 비용 최적화
Autocomplete (New) 서비스 사용 비용을 최적화하려면 Place Details (New) 및 Autocomplete (New) 위젯에서 필드 마스크를 사용하여 필요한 Autocomplete (New) 데이터 필드만 반환하세요.
고급 비용 최적화
SKU: Autocomplete Request 가격에 액세스하고 Place Details (New) 대신 선택된 장소에 대한 Geocoding API 결과를 요청하려면 Autocomplete (New)를 프로그래매틱 방식으로 구현해 보세요. Geocoding API와 연결된 요청당 가격은 다음 두 조건이 모두 충족되는 경우 세션당 (세션 기반) 가격보다 비용 효과적입니다.
- 사용자가 선택한 장소의 위도/경도 또는 주소만 필요한 경우 Geocoding API는 장소 세부정보 (신규) 호출보다 낮은 비용으로 이 정보를 제공합니다.
- 사용자가 평균 네 개 이하의 자동 완성 (신규) 예상 검색어 요청 내에서 자동 완성 예상 검색어를 선택하면 요청당 가격이 세션당 가격보다 비용 효과적일 수 있습니다.
애플리케이션에 선택된 예상 검색어의 주소 및 위도/경도 이외의 정보가 필요한가요?
예, 추가 세부정보가 필요합니다.
세션 기반 Autocomplete (신규)를 장소 세부정보 (신규)와 함께 사용
애플리케이션에 장소 이름, 비즈니스 상태, 영업시간과 같은 Place Details (New)가 필요하므로 Autocomplete (New) 구현에서는 세션 토큰(프로그래매틱 방식 또는 JavaScript, Android, iOS 위젯에 내장됨)세션당과 요청하는 장소 데이터 필드에 따라 적용 가능한 Places SKU를 사용해야 합니다.1
위젯 구현
세션 관리는
JavaScript,
Android,
또는 iOS
위젯에 자동으로 내장됩니다. 여기에는 선택된 예상 검색어에 대한 Autocomplete (신규) 요청 및 Place Details (신규) 요청이 모두 포함됩니다. 필요한 Autocomplete (New) 데이터 필드만 요청하도록 하려면 fields 매개변수를 지정해야 합니다.
프로그래매틱 구현
Autocomplete (New) 요청에
세션 토큰을
사용합니다. 선택된 예상 검색어에 대해 장소 세부정보 (신규)를 요청할 때 다음 매개변수를 포함합니다.
- Autocomplete (신규) 응답의 장소 ID
- Autocomplete (New) 요청에 사용되는 세션 토큰
- 필요한 Autocomplete (신규) 데이터 필드를 지정하는
fields매개변수
아니요, 주소와 위치만 필요합니다.
Autocomplete (New)의 사용 성능에 따라 Geocoding API가 장소 세부정보 (New)보다 애플리케이션에 비용 효과적일 수 있습니다. 모든 애플리케이션의 자동 완성 (신규) 효율성은 사용자가 입력하는 내용, 애플리케이션이 사용되는 위치, 성능 최적화 권장사항이 구현되었는지 여부에 따라 다릅니다.
다음 질문에 답변하려면 애플리케이션에서 Autocomplete (New) 예상 검색어를 선택하기 전에 사용자가 평균적으로 입력하는 문자 수를 분석하세요.
사용자가 평균 네 개 이하의 요청에서 Autocomplete (신규) 예상 검색어를 선택하나요?
예
세션 토큰 없이 프로그래매틱 방식으로 Autocomplete (New)를 구현하고 선택한 장소 예상 검색어에 대해 Geocoding API 호출
Geocoding API는 주소 및 위도/경도 좌표를 제공합니다.
Autocomplete 요청을 4회 요청하고 선택한 장소 예상 검색어에 대해 Geocoding API를 호출하는 비용은 세션당 Autocomplete (신규) 비용보다 저렴합니다.1
성능 권장사항을 사용하여 사용자가 훨씬 적은 수의 문자로 원하는 예상 검색어를 가져올 수 있도록 도와주세요.
아니요
세션 기반 Autocomplete (신규)를 장소 세부정보 (신규)와 함께 사용
사용자가 Autocomplete (신규) 예상 검색어를 선택하기 전에 발생할 것으로 예상되는 평균 요청 수가 세션당 가격의 비용을 초과하므로 Autocomplete (신규) 구현에서는 Autocomplete (신규) 요청과 관련 Place Details (신규) 요청 모두에 세션당 세션 토큰을 사용해야 합니다.
1
위젯 구현
세션 관리는
JavaScript,
Android,
또는 iOS
위젯에 자동으로 내장됩니다. 여기에는 선택된 예상 검색어에 대한 Autocomplete (신규) 요청 및 장소 세부정보 (신규) 요청이 모두 포함됩니다. 필요한 필드만 요청하도록 하려면 fields 매개변수를 지정해야 합니다.
프로그래매틱 구현
Autocomplete (New) 요청에
세션 토큰을 사용합니다.
선택된 예상 검색어에 대해 장소 세부정보 (신규)를 요청할 때 다음 매개변수를 포함합니다.
- Autocomplete (신규) 응답의 장소 ID
- Autocomplete (New) 요청에 사용되는 세션 토큰
- 주소 및 도형과 같은 필드를 지정하는
fields매개변수
Autocomplete (New) 요청 지연 고려
사용자가 처음 3~4자를 입력할 때까지 Autocomplete (New) 요청을 지연하는 것과 같은 전략을 채택하여 애플리케이션에서 요청하는 횟수를 줄일 수 있습니다. 예를 들어 사용자가 세 번째 문자를 입력한 후에 각 문자에 대해 Autocomplete (New) 요청을 하면 사용자가 7개의 문자를 입력한 후 Geocoding API 요청을 한 예상 검색어를 선택하는 경우 총비용은 Autocomplete (New) Per Request 4개 + Geocoding에 대한 비용이 됩니다.1
요청을 지연하면 평균 프로그래매틱 요청 수가 네 개 미만이 될 수 있는 경우 Geocoding API를 사용한 고성능 Autocomplete (New) 구현을 위한 안내를 따르세요. 키를 입력할 때마다 예상 검색어가 표시될 것이라고 예상하는 사용자는 요청 지연을 지연 시간으로 인식할 수 있습니다.
성능 권장사항을 사용하여 사용자가 더 적은 수의 문자로 원하는 예상 검색어를 가져올 수 있도록 도와주세요.
-
비용은 Google Maps Platform 가격 목록을 참고하세요.
성능 권장사항
다음 가이드라인에서는 Autocomplete (New) 성능을 최적화하는 방법을 설명합니다.
- Autocomplete (New) 구현에 국가별 제한사항, 위치 상세 검색, (프로그래매틱 구현의 경우) 언어 환경설정을 추가합니다. 위젯은 사용자의 브라우저 또는 휴대기기에서 언어 환경설정을 선택하므로 언어 환경설정이 필요하지 않습니다.
- Autocomplete (New)에 지도와 함께 제공된 경우 지도 표시 영역별로 위치를 상세 검색할 수 있습니다.
- 예상 검색어 중 원하는 결과 주소가 없어 사용자가 자동 완성 (신규) 예상 검색어 중 하나를 선택하지 않는 경우 원래 사용자 입력을 재사용하여 더 관련성 높은 결과를 얻을 수 있습니다.
- 사용자가 주소 정보만 입력할 것으로 예상되는 경우 Geocoding API 호출 시 원래 사용자 입력을 재사용합니다.
- 사용자가 이름 또는 주소로 특정 장소에 대한 쿼리를 입력할 것으로 예상되는 경우 장소 세부정보 (신규) 요청을 사용합니다. 특정 지역에서만 결과가 예상되는 경우 위치 상세 검색을 사용합니다.
- 건물 내 특정 단위 또는 아파트 주소와 같은 하위 건물 주소를 입력하는 사용자 예를 들어 체코 주소인 'Stroupežnického 3191/17, Praha'를 바탕으로 Autocomplete (신규)에서 부분 예측이 이루어집니다.
- 사용자가 뉴욕시의 '23-30 29th St, Queens' 또는 하와이 카우아이섬의 '47-380 Kamehameha Hwy, Kaneohe'처럼 도로 구간 접두사가 있는 주소를 입력하는 경우
위치 편향
location 매개변수와 radius 매개변수를 전달하여 지정된 지역에 편중된 결과를 얻을 수 있습니다. 이렇게 하면 자동 완성 (신규)이 정의된 영역 내의 결과를 표시하도록 선호합니다. 정의된 영역 밖의 결과가 표시될 수도 있습니다. components 매개변수를 사용하여 결과를 필터링하여 지정된 국가 내의 장소만 표시할 수 있습니다.
위치 제한
locationRestriction 매개변수를 전달하여 결과를 지정된 영역으로 제한합니다.
location 및 radius 매개변수로 정의된 지역으로 결과를 제한하려면 locationRestriction 매개변수를 추가하세요. 이렇게 하면 자동 완성 (신규)이 해당 지역 내의 결과만 반환하도록 지시합니다.