住宅区查看器

在此示例中,我们为地址添加了地点自动补全搜索栏,以便用户输入地址并评估附近的设施。对于住宅用户,我们将 placeTypePreferences 设置为通常与家庭生活相关联的类型。此示例中的地址仅限于美国。

了解代码

调整地点类型的显示频率

在指定 Local Context Library 要返回的地点类型时,您可以使用 weight 属性为每个属性分配相对权重(相对权重较高的类型会更频繁地显示)。此示例为公园和学校(如果有)指定了更高的频率。

TypeScript

placeTypePreferences: [
  { type: "bakery", weight: 1 },
  { type: "bank", weight: 1 },
  { type: "cafe", weight: 2 },
  { type: "department_store", weight: 1 },
  { type: "drugstore", weight: 1 },
  { type: "park", weight: 3 },
  { type: "restaurant", weight: 2 },
  { type: "primary_school", weight: 3 },
  { type: "secondary_school", weight: 3 },
  { type: "supermarket", weight: 2 },
],

JavaScript

placeTypePreferences: [
  { type: "bakery", weight: 1 },
  { type: "bank", weight: 1 },
  { type: "cafe", weight: 2 },
  { type: "department_store", weight: 1 },
  { type: "drugstore", weight: 1 },
  { type: "park", weight: 3 },
  { type: "restaurant", weight: 2 },
  { type: "primary_school", weight: 3 },
  { type: "secondary_school", weight: 3 },
  { type: "supermarket", weight: 2 },
],

地点自动补全

要使用地点自动补全服务,必须先加载 Maps JavaScript API 地点库。Autocomplete 文档详细介绍了可用于自定义地点自动补全行为的所有参数,例如按地理位置或地点类型过滤预测结果。

  1. 为您的项目启用 Places API
  2. 除了 Local Context Library 之外,还应加载 JavaScript API 地点库。

<script async
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=localContext,places&v=beta&callback=initMap">
</script>

  1. 请参阅 Autocomplete 文档代码示例,了解如何向您的网站或地图添加地点自动补全搜索栏。在此示例中,相关行如下:

TypeScript

// Build and add the Autocomplete search bar
const input = document.getElementById("input")! as HTMLInputElement;
const options = {
  types: ["address"],
  componentRestrictions: {
    country: "us",
  },
  fields: ["address_components", "geometry", "name"],
};
const autocomplete = new google.maps.places.Autocomplete(input, options);

JavaScript

// Build and add the Autocomplete search bar
const input = document.getElementById("input");
const options = {
  types: ["address"],
  componentRestrictions: {
    country: "us",
  },
  fields: ["address_components", "geometry", "name"],
};
const autocomplete = new google.maps.places.Autocomplete(input, options);

试用示例