基本地点自动补全元素

请选择平台: Android iOS JavaScript

BasicPlaceAutocompleteElement 会创建一个文本输入字段,在界面选择列表中提供地点预测结果,并返回所选地点的地点 ID。

PlaceAutocompleteElement 相比,基本地点自动补全元素的实现方式更简单,并且在以下方面有所不同:

  • 基本地点自动补全元素返回一个仅包含地点 ID地点对象,而不是 PlacePrediction 对象。您可以直接将返回的地点 ID 与 Places UI Kit 详情元素搭配使用,以获取更多地点详情;而 PlacePrediction 对象则需要先转换为地点 ID。
  • 基本地点自动补全元素不需要您加载 Places API。
  • 当用户选择地点预测结果时,基本地点自动补全元素会清除输入字段。

前提条件

如需使用基本地点自动补全元素,您必须在 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);

向地图添加基本 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>

限制自动补全预测结果

默认情况下,基本地点自动补全服务会显示所有地点类型(偏向于用户所在位置附近的预测结果)。通过限制或自定义调整结果来设置 BasicPlaceAutocompleteElementOptions,可以显示更相关的预测结果。

限制预测结果会导致基本自动补全元素忽略限制区域以外的任何结果。常见做法是将结果范围限定在地图边界内。自定义调整结果会使 BasicAutocomplete 元素显示指定区域内的结果,但某些匹配项可能不在这个指定区域内。

如果您未提供任何边界或地图视口,该 API 将尝试根据用户的 IP 地址检测其位置,并使结果偏向于该位置。尽可能设置边界。否则,不同的用户可能会收到不同的预测结果。此外,为了提升总体预测结果准确性,请务必提供合理的视口,例如您通过在地图上平移或缩放来设置的视口,或开发者根据设备位置和半径设置的视口。如果没有半径数据,可将 5 公里视为基本地点自动补全元素的合理默认选项。 请勿设置半径为零(单点)的视口、仅跨几米(100 米以内)的视口,也不要设置横跨全球的视口。

按国家/地区限制地点搜索

如要将地点搜索限定在一个或多个特定国家/地区,请使用 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

配置地点请求元素

添加一个监听器,以便在用户选择预测结果时更新地点请求元素:

// 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>

试用示例