Place Autocomplete(従来版)
コレクションでコンテンツを整理
必要に応じて、コンテンツの保存と分類を行います。
欧州経済領域(EEA)のデベロッパー
注: サーバーサイド ライブラリ
このページでは、Maps JavaScript API で使用可能なクライアントサイド ライブラリについて説明します。サーバーで Places API ウェブサービスを使用する場合は、Google マップサービス向け Node.js クライアントをご覧ください。このページでは、Google マップサービス用の Java Client、Python Client、Go Client も紹介しています。
はじめに
予測入力は、Maps JavaScript API のプレイス ライブラリの機能です。予測入力を使用すると、Google マップの検索フィールドの逐次検索機能をアプリケーションに組み込むことができます。予測入力サービスは、完全な単語や部分文字列を照合して、場所の名前や住所、Plus Codes を解決できます。これにより、アプリケーションはユーザーが入力を始めるとクエリを送信し、候補となる場所を即座に返すことができます。Places API で定義されているように、「場所」とは、施設、地理的位置、有名なスポットなどを指します。
スタートガイド
Maps JavaScript API でプレイス ライブラリを使用するにはまず、Maps JavaScript API を設定した同じプロジェクトで Places API が有効になっていることを Google Cloud コンソールで確認します。
主な違いは、選択リストに表示される結果です。SearchBox は、予測リストを拡張して提供します。つまり Places API で定義される場所に加えて、検索キーワードの候補も表示します。たとえば、ユーザーが「東京のピ」まで入力すると、選択リストには「東京のピザ屋」という語句が含まれ、さらにさまざまなピザ販売店の名前が含まれます。
constcenter={lat:50.064192,lng:-130.605469};// Create a bounding box with sides ~10km away from the center pointconstdefaultBounds={north:center.lat+0.1,south:center.lat-0.1,east:center.lng+0.1,west:center.lng-0.1,};constinput=document.getElementById("pac-input")asHTMLInputElement;constoptions={bounds:defaultBounds,componentRestrictions:{country:"us"},fields:["address_components","geometry","icon","name"],strictBounds:false,};constautocomplete=newgoogle.maps.places.Autocomplete(input,options);
constcenter={lat:50.064192,lng:-130.605469};// Create a bounding box with sides ~10km away from the center pointconstdefaultBounds={north:center.lat+0.1,south:center.lat-0.1,east:center.lng+0.1,west:center.lng-0.1,};constinput=document.getElementById("pac-input");constoptions={bounds:defaultBounds,componentRestrictions:{country:"us"},fields:["address_components","geometry","icon","name"],strictBounds:false,};constautocomplete=newgoogle.maps.places.Autocomplete(input,options);
functionfillInAddress(){// Get the place details from the autocomplete object.constplace=autocomplete.getPlace();letaddress1="";letpostcode="";// Get each component of the address from the place details,// and then fill-in the corresponding field on the form.// place.address_components are google.maps.GeocoderAddressComponent objects// which are documented at http://goo.gle/3l5i5Mrfor(constcomponentofplace.address_componentsasgoogle.maps.GeocoderAddressComponent[]){// @ts-ignore remove once typings fixedconstcomponentType=component.types[0];switch(componentType){case"street_number":{address1=`${component.long_name}${address1}`;break;}case"route":{address1+=component.short_name;break;}case"postal_code":{postcode=`${component.long_name}${postcode}`;break;}case"postal_code_suffix":{postcode=`${postcode}-${component.long_name}`;break;}case"locality":(document.querySelector("#locality")asHTMLInputElement).value=component.long_name;break;case"administrative_area_level_1":{(document.querySelector("#state")asHTMLInputElement).value=component.short_name;break;}case"country":(document.querySelector("#country")asHTMLInputElement).value=component.long_name;break;}}address1Field.value=address1;postalField.value=postcode;// After filling the form with address components from the Autocomplete// prediction, set cursor focus on the second address line to encourage// entry of subpremise information such as apartment, unit, or floor number.address2Field.focus();}
functionfillInAddress(){// Get the place details from the autocomplete object.constplace=autocomplete.getPlace();letaddress1="";letpostcode="";// Get each component of the address from the place details,// and then fill-in the corresponding field on the form.// place.address_components are google.maps.GeocoderAddressComponent objects// which are documented at http://goo.gle/3l5i5Mrfor(constcomponentofplace.address_components){// @ts-ignore remove once typings fixedconstcomponentType=component.types[0];switch(componentType){case"street_number":{address1=`${component.long_name}${address1}`;break;}case"route":{address1+=component.short_name;break;}case"postal_code":{postcode=`${component.long_name}${postcode}`;break;}case"postal_code_suffix":{postcode=`${postcode}-${component.long_name}`;break;}case"locality":document.querySelector("#locality").value=component.long_name;break;case"administrative_area_level_1":{document.querySelector("#state").value=component.short_name;break;}case"country":document.querySelector("#country").value=component.long_name;break;}}address1Field.value=address1;postalField.value=postcode;// After filling the form with address components from the Autocomplete// prediction, set cursor focus on the second address line to encourage// entry of subpremise information such as apartment, unit, or floor number.address2Field.focus();}window.initAutocomplete=initAutocomplete;
// Listen for the event fired when the user selects a prediction and retrieve// more details for that place.searchBox.addListener("places_changed",()=>{constplaces=searchBox.getPlaces();if(places.length==0){return;}// Clear out the old markers.markers.forEach((marker)=>{marker.setMap(null);});markers=[];// For each place, get the icon, name and location.constbounds=newgoogle.maps.LatLngBounds();places.forEach((place)=>{if(!place.geometry||!place.geometry.location){console.log("Returned place contains no geometry");return;}consticon={url:place.iconasstring,size:newgoogle.maps.Size(71,71),origin:newgoogle.maps.Point(0,0),anchor:newgoogle.maps.Point(17,34),scaledSize:newgoogle.maps.Size(25,25),};// Create a marker for each place.markers.push(newgoogle.maps.Marker({map,icon,title:place.name,position:place.geometry.location,}));if(place.geometry.viewport){// Only geocodes have viewport.bounds.union(place.geometry.viewport);}else{bounds.extend(place.geometry.location);}});map.fitBounds(bounds);});
// Listen for the event fired when the user selects a prediction and retrieve// more details for that place.searchBox.addListener("places_changed",()=>{constplaces=searchBox.getPlaces();if(places.length==0){return;}// Clear out the old markers.markers.forEach((marker)=>{marker.setMap(null);});markers=[];// For each place, get the icon, name and location.constbounds=newgoogle.maps.LatLngBounds();places.forEach((place)=>{if(!place.geometry||!place.geometry.location){console.log("Returned place contains no geometry");return;}consticon={url:place.icon,size:newgoogle.maps.Size(71,71),origin:newgoogle.maps.Point(0,0),anchor:newgoogle.maps.Point(17,34),scaledSize:newgoogle.maps.Size(25,25),};// Create a marker for each place.markers.push(newgoogle.maps.Marker({map,icon,title:place.name,position:place.geometry.location,}),);if(place.geometry.viewport){// Only geocodes have viewport.bounds.union(place.geometry.viewport);}else{bounds.extend(place.geometry.location);}});map.fitBounds(bounds);});
getPlacePredictions() は、場所の予測を返します。注: 「場所」とは、Places API で定義されるように、施設、地理的位置、有名なスポットなどを指します。
getQueryPredictions() は拡張された予測リストを返します。これには Places API で定義される場所に加えて、検索語句の候補を含めることができます。たとえば、ユーザーが「東京のピ」まで入力すると、選択リストには「東京のピザ屋」という語句が含まれ、さらにさまざまなピザ販売店の名前が含まれます。
// This example retrieves autocomplete predictions programmatically from the// autocomplete service, and displays them as an HTML list.// This example requires the Places library. Include the libraries=places// parameter when you first load the API. For example:// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">functioninitService():void{constdisplaySuggestions=function(predictions:google.maps.places.QueryAutocompletePrediction[]|null,status:google.maps.places.PlacesServiceStatus){if(status!=google.maps.places.PlacesServiceStatus.OK||!predictions){alert(status);return;}predictions.forEach((prediction)=>{constli=document.createElement("li");li.appendChild(document.createTextNode(prediction.description));(document.getElementById("results")asHTMLUListElement).appendChild(li);});};constservice=newgoogle.maps.places.AutocompleteService();service.getQueryPredictions({input:"pizza near Syd"},displaySuggestions);}declareglobal{interfaceWindow{initService:()=>void;}}window.initService=initService;
// This example retrieves autocomplete predictions programmatically from the// autocomplete service, and displays them as an HTML list.// This example requires the Places library. Include the libraries=places// parameter when you first load the API. For example:// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">functioninitService(){constdisplaySuggestions=function(predictions,status){if(status!=google.maps.places.PlacesServiceStatus.OK||!predictions){alert(status);return;}predictions.forEach((prediction)=>{constli=document.createElement("li");li.appendChild(document.createTextNode(prediction.description));document.getElementById("results").appendChild(li);});};constservice=newgoogle.maps.places.AutocompleteService();service.getQueryPredictions({input:"pizza near Syd"},displaySuggestions);}window.initService=initService;
<html>
<head>
<title>Retrieving Autocomplete Predictions</title>
<link rel="stylesheet" type="text/css" href="./style.css" />
<script type="module" src="./index.js"></script>
</head>
<body>
<p>Query suggestions for 'pizza near Syd':</p>
<ul id="results"></ul>
<!-- Replace Powered By Google image src with self hosted image. https://developers.google.com/maps/documentation/places/web-service/policies#other_attribution_requirements -->
<img
class="powered-by-google"
src="https://storage.googleapis.com/geo-devrel-public-buckets/powered_by_google_on_white.png"
alt="Powered by Google"
/>
<!--
The `defer` attribute causes the script to execute after the full HTML
document has been parsed. For non-blocking uses, avoiding race conditions,
and consistent behavior across browsers, consider loading using Promises. See
https://developers.google.com/maps/documentation/javascript/load-maps-js-api
for more information.
-->
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB41DRUbKWJHPxaFjMAwdrzWzbVKartNGg&callback=initService&libraries=places&v=weekly"
defer
></script>
</body>
</html>
同じセッション トークンを使用して、AutocompleteService.getPlacePredictions() の呼び出しによって返された場所に対して、単一の Place Details リクエストを実行する必要があります。この場合、予測入力リクエストは Place Details リクエストと統合され、呼び出しは、通常の Place Details リクエストとして課金されます。予測入力リクエストは無料です。リクエストでセッション トークンを使用しない場合、予測入力リクエストと Place Details リクエストの両方に対して課金されます。
// Create a new session token.varsessionToken=newgoogle.maps.places.AutocompleteSessionToken();// Pass the token to the autocomplete service.varautocompleteService=newgoogle.maps.places.AutocompleteService();autocompleteService.getPlacePredictions({input:'pizza near Syd',sessionToken:sessionToken},displaySuggestions);
Place Autocomplete(従来版)サービスの費用を最適化するには、Place Details(従来版)と Place Autocomplete(従来版)ウィジェットのフィールド マスクを使用して、必要な Place Autocomplete(従来版)のデータ フィールドのみを返すよう設定します。
高度な費用の最適化
SKU: Autocomplete - Per Request の料金設定を利用し、Place Details(従来版)の代わりに選択された場所に関する Geocoding API の結果をリクエストするためには、Place Autocomplete(従来版)のプログラマティック実装を行うことをおすすめします。次の両方に該当する場合は、リクエストあたりの料金設定と Geocoding API を組み合わせた方が、セッションあたり(セッション ベース)の料金設定よりも費用対効果が高くなります。
ユーザーが選択した場所の緯度と経度または住所のみが必要な場合。その場合は、Geocoding API の方が、Place Details(従来版)の呼び出しよりも少ないコストでこの情報を提供できます。
ユーザーが Place Autocomplete(従来版)の予測入力候補を平均 4 回以下の予測リクエストで選択した場合、リクエストあたりの料金設定の方がセッションあたりの料金設定よりも費用対効果が高くなります。
アプリケーションの費用を最小限に抑える Place Autocomplete(従来版)の実装を選択するには、次の表でアプリケーションのニーズに一致する行を見つけます。
アプリケーションに必要なもの
ユーザーが予測を選択するまでに実行される Place Autocomplete(従来版)リクエストの平均数
Place Autocomplete(従来版)使用時のパフォーマンスによっては、アプリケーションで Places Details(従来版)を使用するよりも、Geocoding API を使用した方が費用対効果が高くなる場合があります。アプリケーションの Place Autocomplete(従来版)の効率は、ユーザーの入力内容や、アプリケーションが使用される場所、パフォーマンス最適化のベスト プラクティスが導入されているかどうかによって変わります。
表のリクエスト数の平均を求めるには、ユーザーがアプリケーション内で Place Autocomplete(従来版)の予測を選択するまでに、平均でどのくらいの文字数を入力するのかを分析します。
セッション ベースの Place Autocomplete(従来版)と Place Details(従来版)
セッション ベースの Place Autocomplete(従来版)と Place Details(従来版)を併用します。
アプリケーションで Place Details(従来版)(場所の名前、営業状況、営業時間など)が必要な場合、Place Autocomplete(従来版)の実装では、セッションごとにセッション トークン(プログラムまたは JavaScript、Android、iOS ウィジェットに組み込まれたもの)を使用し、リクエストする場所データ フィールドに応じて、該当する Places Data SKU を使用する必要があります。1
ウィジェット実装
セッション管理が JavaScript、Android、または iOS ウィジェットに自動的に組み込まれます。これには、選択された予測結果での Place Autocomplete(従来版)リクエストと Place Details(従来版)リクエストの両方が含まれます。必要な Place Autocomplete(従来版)のデータ フィールドのみをリクエストするように、必ず fields パラメータを指定してください。
プログラマティック実装
Place Autocomplete(従来版)リクエストでセッション トークンを使用します。選択された予測結果に関する Place Details(従来版)をリクエストする際は、次のパラメータを含めます。
必要な Place Autocomplete(従来版)のデータ フィールドを指定する fields パラメータ
リクエストごとの Place Autocomplete(従来版)と Geocoding API
セッション トークンを使用せずにプログラムによって Place Autocomplete(従来版)を実装し、選択された場所の予測で Geocoding API を呼び出します。
Geocoding API は、住所と緯度 / 経度の座標を提供します。
Autocomplete - Per Request のリクエスト 4 件と、選択された場所予測に関する Geocoding API の呼び出しを合わせた料金は、Place Autocomplete(従来版)のセッション 1 回あたりの料金よりも少ないコストです。1
住所のみのアプリケーション向けのセッション ベースの Place Autocomplete(従来版)
セッション ベースの Place Autocomplete(従来版)と Place Details(従来版)を併用します。
ユーザーが Place Autocomplete(従来版)の予測を選択するまでに行うと予想されるリクエストの平均数が、セッションあたりの料金を上回るため、Place Autocomplete(従来版)の実装では、Place Autocomplete(従来版)リクエストと関連する Place Details(従来版)リクエストの両方で、セッションごとにセッション トークンを使用する必要があります。
1
ウィジェット実装
セッション管理が JavaScript、Android、または iOS ウィジェットに自動的に組み込まれます。これには、選択された予測結果での Place Autocomplete(従来版)リクエストと Place Details(従来版)リクエストの両方が含まれます。必要なフィールドのみをリクエストするように、必ず fields パラメータを指定してください。
プログラマティック実装
Place Autocomplete(従来版)リクエストでセッション トークンを使用します。選択された予測結果に関する Place Details(従来版)をリクエストする際は、次のパラメータを含めます。