BasicPlaceAutocompleteElement 会创建一个文本输入字段,在界面选择列表中提供地点预测结果,并返回所选地点的地点 ID。
与
PlaceAutocompleteElement 相比,Basic Place Autocomplete 元素更易于实现,并且在以下方面有所不同:
- Basic 地点自动补全 元素返回一个
Place 对象
,其中仅包含
地点 ID,而不是
PlacePrediction对象。您可以将返回的地点 ID 直接与 Places UI Kit 详情 元素搭配使用,以获取其他地点详情,而PlacePrediction对象 则需要先转换为地点 ID。 - Basic Place Autocomplete 元素不需要您在 Google Cloud 控制台中启用 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 元素,请将
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,可以显示更相关的预测结果。
限制预测结果会导致 Basic Autocomplete 元素忽略 限制区域以外的任何结果。常见做法是将结果范围限定在地图边界内。自定义调整结果 会使 BasicAutocomplete 元素显示指定区域内的结果,但某些匹配项可能不在这个指定区域内。
如果您未提供任何边界或地图视口,该 API 将尝试根据用户的 IP 地址检测其位置,并使结果偏向于该位置。请尽可能设置边界 。否则,不同的用户可能会收到不同的预测结果。此外,为了提升总体预测结果准确性,请务必提供合理的视口,例如您通过在地图上平移或 缩放来设置的视口,或开发者根据设备位置和半径设置的视口。如果没有半径数据,可将 5 公里视为 Basic 地点自动补全元素合理的默认选项。请勿设置半径为零(单点)的视口、仅跨几米 的视口(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。
配置 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>