基本的な Place Autocomplete の要素

プラットフォームを選択: Android iOS JavaScript

BasicPlaceAutocompleteElement は、テキスト入力フィールドを作成したり、UI の選択リストに場所の候補を表示したり、選択した場所のプレイス ID を返したりします。

Basic Place Autocomplete 要素は PlaceAutocompleteElementよりも実装が簡単で、次の点が異なります。

  • Basic Place Autocomplete 要素は、 Place object ではなく、 place ID のみを含む PlacePrediction オブジェクトを返します。返されたプレイス ID は、 Places UI キット Details 要素で直接使用して、場所の詳細情報を取得できます。一方、PlacePrediction オブジェクト の場合は、まずプレイス ID に変換する必要があります。
  • Basic Place Autocomplete 要素では、Google Cloud Console で Places API を有効にする必要はありません。
  • Basic Place Autocomplete 要素は、ユーザーが場所の候補を選択すると、入力フィールドをクリアします。

前提条件

Basic Place Autocomplete 要素を使用するには、Google Cloud プロジェクトで Places UI Kit を有効にする必要があります。詳しくは 始めるをご覧ください。

Basic Place Autocomplete 要素を追加する

このセクションでは、Basic Autocomplete 要素をウェブページまたは地図に追加する方法について説明します。

Basic 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);

Basic Autocomplete 要素を地図に追加する

Basic Autocomplete 要素を地図に追加するには、 BasicPlaceAutocompleteElementgmp-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 を設定すると、表示される結果を制限したり、バイアスを設定したりして、より関連性の高い候補を提示することができます。

制限を適用すると、Basic Autocomplete 要素では指定されたエリア外の 結果は無視されます。一般的な制限方法は、結果を地図の境界内のみに限定することです。バイアスを設定すると、指定されたエリア内の結果が優先的に表示されますが、条件によってはエリア外の候補も提示される場合があります。

境界または地図のビューポートを指定しない場合、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 マップに Basic 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 init() {
    // Asynchronously load required libraries from the Google Maps JS API.
    const [{ AdvancedMarkerElement }, { InfoWindow, Circle }, { Size }] =
        await Promise.all([
            google.maps.importLibrary('marker'),
            google.maps.importLibrary('maps'),
            google.maps.importLibrary('core'),
            google.maps.importLibrary('places'),
        ]);

    // 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,
        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 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;
        if (!location) {
            advancedMarkerElement.position = null;
            return;
        }

        // 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 Circle({
            center: newCenter,
            radius: 10000, // 10km in meters.
        });
    });
}

void init();

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>
        <script>
            // prettier-ignore
            (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: "GOOGLE_MAPS_API_KEY"
            });
        </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>