地点自动补全 widget

欧洲经济区 (EEA) 开发者

地点自动补全 widget 会创建一个文本输入字段,在界面选择列表中提供地点预测结果,并返回地点详情以响应用户的选择。使用地点自动补全 widget 在网页上嵌入一个完整的独立自动补全用户界面。

前提条件

若要使用地点自动补全,您必须在 Google Cloud 项目中启用“Places API(新)”。如需了解详情,请参阅开始使用

最新资讯

地点自动补全在以下方面得到了改进:

  • 自动补全 widget 界面针对文本输入占位符、预测列表徽标和地点预测支持区域本地化(包括 RTL 语言)。
  • 增强了无障碍功能,包括对屏幕阅读器和键盘互动的支持。
  • Autocomplete widget 会返回新的 Place 类,以简化对返回对象的处理。
  • 为移动设备和小屏幕设备提供更好的支持。
  • 更出色的性能和改进的图形外观。

添加自动补全 widget

Autocomplete widget 会创建文本输入字段,在界面选择列表中提供地点预测结果,并通过 gmp-select 监听器返回地点详情以响应用户点击。本部分介绍了如何向网页或 Google 地图添加 Autocomplete widget。

向网页添加自动补全 widget

如要向网页添加 Autocomplete widget,请创建一个新的 google.maps.places.PlaceAutocompleteElement,并将其附加到页面,如以下示例所示:

TypeScript

// Request needed libraries.
await google.maps.importLibrary("places") as google.maps.PlacesLibrary;
// Create the input HTML element, and append it.
const placeAutocomplete = new google.maps.places.PlaceAutocompleteElement({});
document.body.appendChild(placeAutocomplete);

JavaScript

// Request needed libraries.
await google.maps.importLibrary("places");
// Create the input HTML element, and append it.
const placeAutocomplete = new google.maps.places.PlaceAutocompleteElement({});
document.body.appendChild(placeAutocomplete);

查看完整代码示例

向地图添加自动补全 widget

如果您的账单邮寄地址不在欧洲经济区 (EEA),您还可以将自动补全 widget 与 Google 地图搭配使用。

如要向地图添加 Autocomplete widget,请创建一个新的 google.maps.places.PlaceAutocompleteElement 实例,将 PlaceAutocompleteElement 附加到 div,然后将该元素作为自定义控件推送到地图上,如以下示例所示:

TypeScript

// Get the inner map.
innerMap = mapElement.innerMap;
innerMap.setOptions({
  mapTypeControl: false,
});

// Use the bounds_changed event to restrict results to the current map bounds.
google.maps.event.addListener(innerMap, 'bounds_changed', async () => {
  placeAutocomplete.locationRestriction = innerMap.getBounds();
});

JavaScript

// Get the inner map.
innerMap = mapElement.innerMap;
innerMap.setOptions({
    mapTypeControl: false,
});
// Use the bounds_changed event to restrict results to the current map bounds.
google.maps.event.addListener(innerMap, 'bounds_changed', async () => {
    placeAutocomplete.locationRestriction = innerMap.getBounds();
});

查看完整代码示例

限制自动补全预测结果

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

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

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

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

如要将地点搜索限定在一个或多个特定国家/地区,请使用 includedRegionCodes 属性指定国家/地区代码,如以下代码段所示:

const pac = new google.maps.places.PlaceAutocompleteElement({
  includedRegionCodes: ['us', 'au'],
});

将地点搜索限定在地图边界内

如要将地点搜索限定在地图的边界内,请使用 locationRestrictions 属性添加边界,如以下代码段所示:

const pac = new google.maps.places.PlaceAutocompleteElement({
  locationRestriction: map.getBounds(),
});

将范围限定在地图边界内时,请务必添加监听器,以在边界发生变化时更新边界:

map.addListener('bounds_changed', () => {
  autocomplete.locationRestriction = map.getBounds();
});

如要移除 locationRestriction,请将其设置为 null

自定义调整地点搜索结果

使用 locationBias 属性并传递半径,即可自定义调整地点搜索结果,将其限定在一个圆形区域内,如下所示:

const autocomplete = new google.maps.places.PlaceAutocompleteElement({
  locationBias: {radius: 100, center: {lat: 50.064192, lng: -130.605469}},
});

如要移除 locationBias,请将其设置为 null

将地点搜索结果限定为特定类型

使用 includedPrimaryTypes 属性并指定一种或多种类型,即可将地点搜索结果限定为特定类型的地点,如下所示:

const autocomplete = new google.maps.places.PlaceAutocompleteElement({
  includedPrimaryTypes: ['establishment'],
});

如需查看支持的类型的完整列表,请参阅地点类型表 A 和 B

获取地点详情

如要获取所选地点的地点详情,请向 PlaceAutocompleteElement 添加 gmp-select 监听器,如以下示例所示:

TypeScript

// Add the gmp-placeselect listener, and display the results.
//@ts-ignore
placeAutocomplete.addEventListener('gmp-select', async ({ placePrediction }) => {
    const place = placePrediction.toPlace();
    await place.fetchFields({ fields: ['displayName', 'formattedAddress', 'location'] });
    selectedPlaceTitle.textContent = 'Selected Place:';
    selectedPlaceInfo.textContent = JSON.stringify(
        place.toJSON(), /* replacer */ null, /* space */ 2);
});

JavaScript

// Add the gmp-placeselect listener, and display the results.
//@ts-ignore
placeAutocomplete.addEventListener('gmp-select', async ({ placePrediction }) => {
    const place = placePrediction.toPlace();
    await place.fetchFields({ fields: ['displayName', 'formattedAddress', 'location'] });
    selectedPlaceTitle.textContent = 'Selected Place:';
    selectedPlaceInfo.textContent = JSON.stringify(place.toJSON(), /* replacer */ null, /* space */ 2);
});

查看完整代码示例

在前面的示例中,事件监听器会返回 Place 类的对象。调用 place.fetchFields() 即可获取应用所需的地点详情数据字段

下例中的监听器会请求地点信息并将其显示在地图上。

TypeScript

// Add the gmp-placeselect listener, and display the results on the map.
//@ts-ignore
placeAutocomplete.addEventListener('gmp-select', async ({ placePrediction }) => {
    const place = placePrediction.toPlace();
    await place.fetchFields({
      fields: ['displayName', 'formattedAddress', 'location'],
    });

    // If the place has a geometry, then present it on a map.
    if (place.viewport) {
      innerMap.fitBounds(place.viewport);
    } else {
      innerMap.setCenter(place.location);
      innerMap.setZoom(17);
    }

    let content = document.createElement('div');
    let nameText = document.createElement('span');
    nameText.textContent = place.displayName;
    content.appendChild(nameText);
    content.appendChild(document.createElement('br'));
    let addressText = document.createElement('span');
    addressText.textContent = place.formattedAddress;
    content.appendChild(addressText);

    updateInfoWindow(content, place.location);
    marker.position = place.location;
  }
);

JavaScript

// Add the gmp-placeselect listener, and display the results on the map.
//@ts-ignore
placeAutocomplete.addEventListener('gmp-select', async ({ placePrediction }) => {
    const place = placePrediction.toPlace();
    await place.fetchFields({
        fields: ['displayName', 'formattedAddress', 'location'],
    });
    // If the place has a geometry, then present it on a map.
    if (place.viewport) {
        innerMap.fitBounds(place.viewport);
    }
    else {
        innerMap.setCenter(place.location);
        innerMap.setZoom(17);
    }
    let content = document.createElement('div');
    let nameText = document.createElement('span');
    nameText.textContent = place.displayName;
    content.appendChild(nameText);
    content.appendChild(document.createElement('br'));
    let addressText = document.createElement('span');
    addressText.textContent = place.formattedAddress;
    content.appendChild(addressText);
    updateInfoWindow(content, place.location);
    marker.position = place.location;
});

查看完整代码示例

示例地图

本部分包含本页介绍的示例地图的完整代码。

自动补全元素

此示例会向网页添加 Autocomplete widget,并显示每个选定地点的结果。

TypeScript

async function initMap(): Promise<void> {
    // Request needed libraries.
    await google.maps.importLibrary("places") as google.maps.PlacesLibrary;
    // Create the input HTML element, and append it.
    const placeAutocomplete = new google.maps.places.PlaceAutocompleteElement({});
    document.body.appendChild(placeAutocomplete);

    // Inject HTML UI.
    const selectedPlaceTitle = document.createElement('p');
    selectedPlaceTitle.textContent = '';
    document.body.appendChild(selectedPlaceTitle);

    const selectedPlaceInfo = document.createElement('pre');
    selectedPlaceInfo.textContent = '';
    document.body.appendChild(selectedPlaceInfo);

    // Add the gmp-placeselect listener, and display the results.
    //@ts-ignore
    placeAutocomplete.addEventListener('gmp-select', async ({ placePrediction }) => {
        const place = placePrediction.toPlace();
        await place.fetchFields({ fields: ['displayName', 'formattedAddress', 'location'] });
        selectedPlaceTitle.textContent = 'Selected Place:';
        selectedPlaceInfo.textContent = JSON.stringify(
            place.toJSON(), /* replacer */ null, /* space */ 2);
    });
}

initMap();

JavaScript

async function initMap() {
    // Request needed libraries.
    await google.maps.importLibrary("places");
    // Create the input HTML element, and append it.
    const placeAutocomplete = new google.maps.places.PlaceAutocompleteElement({});
    document.body.appendChild(placeAutocomplete);
    // Inject HTML UI.
    const selectedPlaceTitle = document.createElement('p');
    selectedPlaceTitle.textContent = '';
    document.body.appendChild(selectedPlaceTitle);
    const selectedPlaceInfo = document.createElement('pre');
    selectedPlaceInfo.textContent = '';
    document.body.appendChild(selectedPlaceInfo);
    // Add the gmp-placeselect listener, and display the results.
    //@ts-ignore
    placeAutocomplete.addEventListener('gmp-select', async ({ placePrediction }) => {
        const place = placePrediction.toPlace();
        await place.fetchFields({ fields: ['displayName', 'formattedAddress', 'location'] });
        selectedPlaceTitle.textContent = 'Selected Place:';
        selectedPlaceInfo.textContent = JSON.stringify(place.toJSON(), /* replacer */ null, /* space */ 2);
    });
}
initMap();

CSS

/* 
 * Always set the map height explicitly to define the size of the div element
 * that contains the map. 
 */
#map {
  height: 100%;
}

/* 
 * Optional: Makes the sample page fill the window. 
 */
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

p {
  font-family: Roboto, sans-serif;
  font-weight: bold;
}

HTML

<html>
  <head>
    <title>Place Autocomplete element</title>

    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script type="module" src="./index.js"></script>
  </head>
  <body>
    <p style="font-family: roboto, sans-serif">Search for a place here:</p>

    <!-- 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>
  </body>
</html>

试用示例

自动补全地图

以下示例展示了如何向 Google 地图添加 Autocomplete widget。

TypeScript

const mapElement = document.querySelector('gmp-map') as google.maps.MapElement;
const placeAutocomplete = document.querySelector(
  'gmp-place-autocomplete'
) as google.maps.places.PlaceAutocompleteElement;
let innerMap;
let marker: google.maps.marker.AdvancedMarkerElement;
let infoWindow: google.maps.InfoWindow;
let center = { lat: 40.749933, lng: -73.98633 }; // New York City
async function initMap(): Promise<void> {
  // Request needed libraries.
  const [] = await Promise.all([
    google.maps.importLibrary('marker'),
    google.maps.importLibrary('places'),
  ]);

  // Get the inner map.
  innerMap = mapElement.innerMap;
  innerMap.setOptions({
    mapTypeControl: false,
  });

  // Use the bounds_changed event to restrict results to the current map bounds.
  google.maps.event.addListener(innerMap, 'bounds_changed', async () => {
    placeAutocomplete.locationRestriction = innerMap.getBounds();
  });

  // Create the marker and infowindow.
  marker = new google.maps.marker.AdvancedMarkerElement({
    map: innerMap,
  });

  infoWindow = new google.maps.InfoWindow({});

  // Add the gmp-placeselect listener, and display the results on the map.
  //@ts-ignore
  placeAutocomplete.addEventListener('gmp-select', async ({ placePrediction }) => {
      const place = placePrediction.toPlace();
      await place.fetchFields({
        fields: ['displayName', 'formattedAddress', 'location'],
      });

      // If the place has a geometry, then present it on a map.
      if (place.viewport) {
        innerMap.fitBounds(place.viewport);
      } else {
        innerMap.setCenter(place.location);
        innerMap.setZoom(17);
      }

      let content = document.createElement('div');
      let nameText = document.createElement('span');
      nameText.textContent = place.displayName;
      content.appendChild(nameText);
      content.appendChild(document.createElement('br'));
      let addressText = document.createElement('span');
      addressText.textContent = place.formattedAddress;
      content.appendChild(addressText);

      updateInfoWindow(content, place.location);
      marker.position = place.location;
    }
  );
}

// Helper function to create an info window.
function updateInfoWindow(content, center) {
  infoWindow.setContent(content);
  infoWindow.setPosition(center);
  infoWindow.open({
    map: innerMap,
    anchor: marker,
    shouldFocus: false,
  });
}

initMap();

JavaScript

const mapElement = document.querySelector('gmp-map');
const placeAutocomplete = document.querySelector('gmp-place-autocomplete');
let innerMap;
let marker;
let infoWindow;
let center = { lat: 40.749933, lng: -73.98633 }; // New York City
async function initMap() {
    // Request needed libraries.
    const [] = await Promise.all([
        google.maps.importLibrary('marker'),
        google.maps.importLibrary('places'),
    ]);
    // Get the inner map.
    innerMap = mapElement.innerMap;
    innerMap.setOptions({
        mapTypeControl: false,
    });
    // Use the bounds_changed event to restrict results to the current map bounds.
    google.maps.event.addListener(innerMap, 'bounds_changed', async () => {
        placeAutocomplete.locationRestriction = innerMap.getBounds();
    });
    // Create the marker and infowindow.
    marker = new google.maps.marker.AdvancedMarkerElement({
        map: innerMap,
    });
    infoWindow = new google.maps.InfoWindow({});
    // Add the gmp-placeselect listener, and display the results on the map.
    //@ts-ignore
    placeAutocomplete.addEventListener('gmp-select', async ({ placePrediction }) => {
        const place = placePrediction.toPlace();
        await place.fetchFields({
            fields: ['displayName', 'formattedAddress', 'location'],
        });
        // If the place has a geometry, then present it on a map.
        if (place.viewport) {
            innerMap.fitBounds(place.viewport);
        }
        else {
            innerMap.setCenter(place.location);
            innerMap.setZoom(17);
        }
        let content = document.createElement('div');
        let nameText = document.createElement('span');
        nameText.textContent = place.displayName;
        content.appendChild(nameText);
        content.appendChild(document.createElement('br'));
        let addressText = document.createElement('span');
        addressText.textContent = place.formattedAddress;
        content.appendChild(addressText);
        updateInfoWindow(content, place.location);
        marker.position = place.location;
    });
}
// Helper function to create an info window.
function updateInfoWindow(content, center) {
    infoWindow.setContent(content);
    infoWindow.setPosition(center);
    infoWindow.open({
        map: innerMap,
        anchor: marker,
        shouldFocus: false,
    });
}
initMap();

CSS

/* 
 * Always set the map height explicitly to define the size of the div element
 * that contains the map. 
 */
gmp-map {
  height: 100%;
}

/* 
 * Optional: Makes the sample page fill the window. 
 */
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

.place-autocomplete-card {
  background-color: #fff;
  border-radius: 5px;
  box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px;
  margin: 10px;
  padding: 5px;
  font-family: Roboto, sans-serif;
  font-size: large;
  font-weight: bold;
}

gmp-place-autocomplete {
  width: 300px;
}

#infowindow-content .title {
  font-weight: bold;
}

#map #infowindow-content {
  display: inline;
}

HTML

<html>
  <head>
    <title>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 center="40.749933,-73.98633" zoom="13" map-id="DEMO_MAP_ID">
      <div
        class="place-autocomplete-card"
        slot="control-inline-start-block-start">
        <p>Search for a place here:</p>
        <gmp-place-autocomplete></gmp-place-autocomplete>
      </div>
    </gmp-map>
  </body>
</html>

试用示例

使用地点选择器组件

地点选择器组件是一个文本输入字段,最终用户可以使用自动补全功能搜索特定地址或地点。它是扩展组件库的一部分,该库是一组 Web 组件,可帮助开发者更快速地构建更出色的地图和位置功能。

使用地点选择器配置器为自定义地点选择器组件创建可嵌入的代码,然后导出该代码以用于 React 和 Angular 等热门框架或完全不使用框架。