BasicPlaceAutocompleteElement
は、テキスト入力フィールドを作成し、UI の選択リストに場所の候補を表示して、選択した場所のプレイス ID を返します。
基本的な Place Autocomplete 要素は
PlaceAutocompleteElement
よりも実装が簡単で、次の点で異なります。
- Basic Place Autocomplete 要素は、
PlacePrediction
オブジェクトではなく、プレイス ID のみを含む Place オブジェクトを返します。返されたプレイス ID は、Places UI Kit Details 要素で直接使用して、場所の詳細情報を取得できます。一方、PlacePrediction
オブジェクトは、まずプレイス ID に変換する必要があります。 - Basic Place Autocomplete 要素では、Places API を読み込む必要はありません。
- Basic Place Autocomplete 要素は、ユーザーが場所の候補を選択すると入力フィールドをクリアします。
前提条件
基本的な Place Autocomplete 要素を使用するには、Google Cloud プロジェクトで Places UI Kit を有効にする必要があります。詳しくは、 スタートガイドをご覧ください。
基本的な Place Autocomplete 要素を追加する
このセクションでは、基本の Autocomplete 要素をウェブページまたは地図に追加する方法について説明します。
基本的な Autocomplete 要素をウェブページに追加する
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);
基本的な Autocomplete 要素を地図に追加する
基本的な Autocomplete 要素を地図に追加するには、次の例に示すように、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
を設定すると、表示される結果を制限したり、バイアスを設定したりして、より関連性の高い候補を提示することができます。
制限を適用すると、基本的なオートコンプリート要素では指定されたエリア外の結果は無視されます。一般的な制限方法は、結果を地図の境界内のみに限定することです。バイアスを設定すると、指定されたエリア内の結果が優先的に表示されますが、条件によってはエリア外の候補も提示される場合があります。
境界または地図のビューポートを指定しない場合、API は IP アドレスからユーザーの位置を検出し、その位置を優先して結果を返します。境界は可能な限り指定しましょう。指定しなかった場合、表示される候補がユーザーごとに変化する可能性があります。また、一般的に予測精度を高めるためには、地図のパンまたはズームによって設定したような実用的なビューポート、またはデバイスの位置と半径に基づいたデベロッパーによるビューポートを提供することが重要です。半径を指定できない場合は、5 km が Basic Place Autocomplete 要素の有効なデフォルト値とみなされます。半径が 0 のビューポート(単一ポイント)、100 m 未満のビューポート、地球にまたがるビューポートは設定しないでください。
Place Search の結果を特定の国に限定する
Place Search の結果を 1 つ以上の国に限定するには、includedRegionCodes
プロパティを使用して国コードを指定します。以下のスニペットをご覧ください。
const pac = new google.maps.places.BasicPlaceAutocompleteElement({ includedRegionCodes: ['us', 'au'], });
Place Search の結果を地図の境界内に限定する
Place Search の結果を地図の境界内に限定するには、locationRestrictions
プロパティを使用して境界を追加します。以下のスニペットをご覧ください。
const pac = new google.maps.places.BasicPlaceAutocompleteElement({ locationRestriction: map.getBounds(), });
地図の境界内に限定する場合は、リスナーを追加して、境界が変更されたときに境界が更新されるようにしてください。
map.addListener('bounds_changed', () => { autocomplete.locationRestriction = map.getBounds(); });
locationRestriction
を削除するには、null
に設定します。
Place Search の結果にバイアスを設定する
Place Search の結果に円で囲まれた地域を優先的に表示するには、locationBias
プロパティを使用して、半径を渡します。コードは以下のようになります。
const autocomplete = new google.maps.places.BasicPlaceAutocompleteElement({ locationBias: {radius: 100, center: {lat: 50.064192, lng: -130.605469}}, });
locationBias
を削除するには、null
に設定します。
Place Search の結果を特定のタイプに限定する
Place Search の結果を特定の場所のタイプに限定するには、includedPrimaryTypes
プロパティを使用して、1 つ以上のタイプを指定します。コードは以下のようになります。
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 マップに基本的な Autocomplete 要素を追加する方法を示しています。
JavaScript
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>