地点自动补全(新)

请选择平台: Android iOS JavaScript 网络服务

“自动补全(新)”服务是一项 iOS API,可在响应请求时返回地点建议。在请求中,指定文本搜索字符串和用于控制搜索区域的地理边界。

“自动补全(新)”服务可以根据输入的完整字词和子字符串进行匹配,从而解析地点名称、地址和 Plus Codes。这样,应用就可以在用户输入内容时发送查询,从而即时提供地点建议。

地点建议是指系统根据指定的输入文本字符串和搜索区域提供的地点,例如商家、地址和地图注点。

例如,您可以使用包含部分用户输入“Spagh”的字符串作为输入来调用该 API,并将搜索区域限制为纽约市。然后,响应中会包含与搜索字符串和搜索区域匹配的地点建议列表(例如名为“Cafe Spaghetti”的餐厅),以及相应地点的详细信息。

系统会向用户显示返回的地点建议,以便他们选择所需的地点。您可以发出地点详情(新)请求,详细了解所返回的任何地点建议。

“自动补全(新)”请求

通过对 GMSPlaceClient 调用方法来创建自动补全请求。您可以在 GMSAutocompleteRequest 对象中传递参数。响应会在 GMSAutocompletePlaceSuggestion 对象中提供自动补全建议。

API 密钥和 query 参数是必需的。您还可以添加 GMSAutocompleteSessionToken 以将请求与结算会话相关联,并添加 GMSAutocompleteFilter 以应用于结果。

如需详细了解必需参数和可选参数,请参阅本文档的“参数”部分

Swift

let token = GMSAutocompleteSessionToken()

let northWestBounds = CLLocationCoordinate2DMake(40.921628, -73.700051)
let southEastBounds = CLLocationCoordinate2DMake(40.477398, -74.259087)

let filter = GMSAutocompleteFilter()
filter.types = [kGMSPlaceTypeRestaurant]
filter.locationBias = GMSPlaceRectangularLocationOption(northWestBounds, southEastBounds)
    
let request = GMSAutocompleteRequest(query:"Spagh")
request.filter = filter
request.sessionToken = token

GMSPlacesClient.shared().fetchAutocompleteSuggestions(from: request, callback: { ( results, error ) in
      if let error = error {
        print("Autocomplete error: \(error)")
        return
      }
      if let autocompleteResults = results {
        for result in autocompleteResults {
          print("Result \(String(describing: result.placeSuggestion?.placeID)) with \(String(describing: result.placeSuggestion?.attributedFullText))")
        }
      }
    })

Objective-C

CLLocationCoordinate2D northEast = CLLocationCoordinate2DMake(37.388162, -122.088137);
CLLocationCoordinate2D southWest = CLLocationCoordinate2DMake(37.395804, -122.077023);

GMSAutocompleteFilter *filter = [[GMSAutocompleteFilter alloc] init];
filter.types = @[ kGMSPlaceTypeRestaurant ];
filter.locationBias = GMSPlaceRectangularLocationOption(northEast, southWest);
GMSAutocompleteRequest *request = [[GMSAutocompleteRequest alloc] initWithQuery:@"Sicilian piz"];
request.sessionToken = token;
request.filter = filter;

[[GMSPlacesClient sharedClient] fetchAutocompleteSuggestionsFromRequest:request callback:^(NSArray<GMSAutocompleteSuggestion *> * results, NSError * error){
  // Handle response
  for (GMSAutocompleteSuggestion *suggestion in results) {
    if (suggestion.placeSuggestion) {
      // Show place suggestion data.
    }
  }
}];

Places Swift SDK for iOS(预览版)

let center = (37.3913916, -122.0879074)
let northEast = (37.388162, -122.088137)
let southWest = (37.395804, -122.077023)

let bias = RectangularCoordinateRegion(northEast: northEast, southWest: southWest)
let filter = AutocompleteFilter(types: [ .restaurant ], origin: center, coordinateRegionBias: bias)

let autocompleteRequest = AutocompleteRequest(query: "Sicilian piz", filter: filter)
switch await placesClient.fetchAutocompleteSuggestions(with: autocompleteRequest) {
case .success(let autocompleteSuggestions):
  // Handle suggestions.
case .failure(let placesError):
  // Handle error.
}

自动补全(新)回复

自动补全功能会返回一个最多包含五个 GMSAutocompleteSuggestion 实例的数组。数组包含:

  • placeID
  • types:适用于此地点的类型。
  • distanceMeters:距离原点的距离。
  • attributedFullText:建议的完整文本,可供用户阅读。
  • attributedPrimaryText:建议的主要文本(人类可读)。
  • attributedSecondaryText:建议的直观易懂的辅助文本。
  • structuredFormat:特定名称和用于消除歧义的文本,例如城市或地区。

必需参数

查询

要搜索的字符串。指定完整字词和子字符串、地点名称、地址和 Plus Codes。自动补全(新)服务会根据此字符串返回候选匹配项,并按照其判断的相关程度对结果排序。

可选参数

类型

地点只能有一个主要类型,该类型必须与表 A表 B 相关联。例如,主要类型可能是 mexican_restaurantsteak_house

默认情况下,该 API 会根据 input 参数返回所有地点,无论与地点关联的主要类型值如何。通过传递 types 参数,将结果限制为特定主要类型或主要类型。

使用此参数可指定 表格 A表格 B 中的最多五个类型值。地点必须与指定的主要类型值之一匹配,才能包含在响应中。

如果出现以下情况,请求会被拒绝并显示 INVALID_REQUEST 错误:

  • 指定了超过五种类型。
  • 指定了任何无法识别的类型。

国家/地区

仅包含指定地区列表中的结果,该列表以最多 15 个 ccTLD(“顶级域名”)双字符值的数组形式指定。如果省略,则不会对响应应用任何限制。例如,如需将地区限制为德国和法国,请执行以下操作:

Swift

let filter = GMSAutocompleteFilter()
filter.countries = ["DE", "FR"]

Objective-C

GMSAutocompleteFilter *filter = [[GMSAutocompleteFilter alloc] init];
filter.countries = @[ @"DE", @"FR" ];

Places Swift SDK for iOS(预览版)

let filter = AutocompleteFilter(countries: ["DE", "FR"])
  

如果您同时指定了 locationRestrictioncountries,则结果位于这两项设置的交叉区域内。

inputOffset

从零开始的 Unicode 字符偏移量,表示 input 中的光标位置。游标位置可能会影响返回的预测结果。如果为空,则默认为 input 的长度。

locationBias 或 locationRestriction

您可以指定 locationBiaslocationRestriction 来定义搜索区域,但不能同时指定这两者。您可以将 locationRestriction 视为指定结果必须位于其中的区域,将 locationBias 视为指定结果必须位于附近但可以位于该区域之外的区域。

  • locationBias 用于指定要搜索的区域。此位置可用作偏向,这意味着系统可以返回指定位置周围的结果,包括指定区域之外的结果。

  • locationRestriction 用于指定要搜索的区域。系统不会返回指定区域以外的结果。

locationBiaslocationRestriction 区域指定为矩形视口或圆形。

圆形由中心点和半径(以米为单位)定义。半径必须介于 0.0 到 50000.0 之间(包括这两个数值)。默认值为 0.0。对于 locationRestriction,您必须将半径设置为大于 0.0 的值。否则,请求将不会返回任何结果。

例如:

Swift

let center = CLLocationCoordinate2DMake(40.730610, -73.935242)
let radius = 1000.0

filter.locationBias = GMSPlaceCircularLocationOption(center, radius)

Objective-C

CLLocationCoordinate2D center = CLLocationCoordinate2DMake(40.730610, -73.935242);
radius = 1000.0;

GMSAutocompleteFilter *filter = [[GMSAutocompleteFilter alloc] init];
filter.locationBias = GMSPlaceCircularLocationOption(center, radius);

Places Swift SDK for iOS(预览版)

let center = CLLocationCoordinate2DMake(40.477398, -74.259087)

let bias = CircularCoordinateRegion(center: center, radius: 1000.0)

let filter = AutocompleteFilter(coordinateRegionBias: bias)      
  

矩形是纬度-经度视口,表示为两个对角线相反的 lowhigh 点。视口被视为封闭区域,即包含其边界。纬度边界必须介于 -90 度到 90 度(包括这两个数值)之间,经度边界必须介于 -180 度到 180 度(包括这两个数值)之间:

  • 如果 low = high,则视口由该单个点组成。
  • 如果 low.longitude > high.longitude,则经度范围会反转(视口跨越 180 度经线)。
  • 如果 low.longitude = -180 度且 high.longitude= 180 度,则视口包含所有经度。
  • 如果 low.longitude = 180 度且 high.longitude = -180 度,则经度范围为空。

必须填充 lowhigh,并且表示的框不能为空。空视口会导致错误。

例如,此视口完全包含纽约市:

Swift

let high = CLLocationCoordinate2DMake(40.921628, -73.700051)
let low = CLLocationCoordinate2DMake(40.477398, -74.259087)

let filter = GMSAutocompleteFilter()
filter.locationBias = GMSPlaceRectangularLocationOption(high, low)

Objective-C

CLLocationCoordinate2D high = CLLocationCoordinate2DMake(40.477398, -74.259087);
CLLocationCoordinate2D low = CLLocationCoordinate2DMake(440.921628, -73.700051);

GMSAutocompleteFilter *filter = [[GMSAutocompleteFilter alloc] init];
filter.locationBias = GMSPlaceRectangularLocationOption(high, low);

Places Swift SDK for iOS(预览版)

let northEast = CLLocationCoordinate2DMake(40.477398, -74.259087)
let southWest = CLLocationCoordinate2DMake(40.921628, -73.700051)

let filter = AutocompleteFilter(coordinateRegionBias: bias)
  

用于计算到目的地的直线距离的起点(返回为 distanceMeters)。如果省略此值,系统将不会返回直线距离。必须指定为经纬度坐标:

Swift

let filter = GMSAutocompleteFilter()
filter.origin =  CLLocation(latitude: 37.395804, longitude: -122.077023)
 

Objective-C

GMSAutocompleteFilter *filter = [[GMSAutocompleteFilter alloc] init];

filter.origin = [[CLLocation alloc] initWithLatitude:37.395804 longitude: -122.077023];

Places Swift SDK for iOS(预览版)

let filter = AutocompleteFilter(origin: CLLocation(latitude: 37.395804, longitude: -122.077023))
  

regionCode

用于设置响应格式的地区代码,以 ccTLD(“顶级域名”)双字符值的形式指定。大多数 ccTLD 代码与 ISO 3166-1 代码相同,但有一些明显的例外。例如,英国的国家代码顶级域名为“uk”(.co.uk),而其 ISO 3166-1 代码却是“gb”(专指“大不列颠及北爱尔兰联合王国”这一实体)。

如果您指定的地区代码无效,则 API 会返回 INVALID_ARGUMENT 错误。此参数可能会根据适用法律影响结果。

sessionToken

会话令牌是用户生成的字符串,用于将“自动补全(新)”调用作为“会话”进行跟踪。“自动补全”(新)使用会话令牌将用户自动补全搜索的查询和选择阶段归入不同的会话,以便进行结算。如需了解详情,请参阅会话令牌

自动补全(新)示例

使用 locationRestriction 和 locationBias

自动补全(新)默认使用 IP 偏向来控制搜索区域。使用 IP 偏向时,API 会使用设备的 IP 地址来偏向结果。您可以选择使用 locationRestrictionlocationBias 指定要搜索的区域,但不能同时使用这两者。

位置限制用于指定要搜索的区域。系统不会返回指定区域以外的结果。以下示例使用位置限制将请求限制为以旧金山为中心、半径为 5000 米的圆形位置限制:

Swift

let token = GMSAutocompleteSessionToken()

let center = CLLocationCoordinate2DMake(37.775061, -122.419400)
let radius = 5000.0

let filter = GMSAutocompleteFilter()
filter.locationRestriction = GMSPlaceCircularLocationOption(center, radius)
    
let request = GMSAutocompleteRequest(query:"Piz")
request.filter = filter
request.sessionToken = token

GMSPlacesClient.shared().fetchAutocompleteSuggestions(from: request, callback: { ( results, error ) in
      if let error = error {
        print("Autocomplete error: \(error)")
        return
      }
      if let autocompleteResults = results {
        for result in autocompleteResults {
          print("Result \(String(describing: result.placeSuggestion?.placeID)) with \(String(describing: result.placeSuggestion?.attributedFullText))")
        }
      }
    })

Objective-C

CLLocationCoordinate2D center = CLLocationCoordinate2DMake(37.775061, -122.419400);
radius = 5000.0;

GMSAutocompleteFilter *filter = [[GMSAutocompleteFilter alloc] init];
filter.locationRestriction = GMSPlaceCircularLocationOption(center, radius);
GMSAutocompleteRequest *request = [[GMSAutocompleteRequest alloc] initWithQuery:@"Sicilian piz"];
request.sessionToken = token;
request.filter = filter;

[[GMSPlacesClient sharedClient] fetchAutocompleteSuggestionsFromRequest:request callback:^(NSArray<GMSAutocompleteSuggestion *> * results, NSError * error){
  // Handle response
  for (GMSAutocompleteSuggestion *suggestion in results) {
    if (suggestion.placeSuggestion) {
      // Show place suggestion data.
    }
  }
}];

Places Swift SDK for iOS(预览版)

let center = (37.775061, -122.419400)
let radius = 5000.0
let restriction = CircularCoordinateRegion(center: center, radius: radius)
let filter = AutocompleteFilter(coordinateRegionRestriction: restriction)
let token = AutocompleteSessionToken()

let autocompleteRequest = AutocompleteRequest(query: "Sicilian piz", sessionToken: token, filter: filter)
switch await placesClient.fetchAutocompleteSuggestions(with: autocompleteRequest) {
case .success(let autocompleteSuggestions):
  for suggestion in autocompleteSuggestions {
    switch suggestion {
    case .place:
      // Show place suggestion data.
    }
  }
case .failure(let placesError):
  // Handle error.
}
  

使用位置偏好设置时,系统会将相应位置作为偏好设置,这意味着系统可以返回指定位置周围的结果,包括指定区域之外的结果。以下示例更改了之前的请求,以使用位置偏好:

Swift

let token = GMSAutocompleteSessionToken()

let center = CLLocationCoordinate2DMake(37.775061, -122.419400)
let radius = 5000.0

let filter = GMSAutocompleteFilter()
filter.locationBias = GMSPlaceCircularLocationOption(center, radius)
    
let request = GMSAutocompleteRequest(query:"Piz")
request.filter = filter
request.sessionToken = token

GMSPlacesClient.shared().fetchAutocompleteSuggestions(from: request, callback: { ( results, error ) in
      if let error = error {
        print("Autocomplete error: \(error)")
        return
      }
      if let autocompleteResults = results {
        for result in autocompleteResults {
          print("Result \(String(describing: result.placeSuggestion?.placeID)) with \(String(describing: result.placeSuggestion?.attributedFullText))")
        }
      }
    })

Objective-C

CLLocationCoordinate2D center = CLLocationCoordinate2DMake(37.775061, -122.419400);
radius = 5000.0;

GMSAutocompleteFilter *filter = [[GMSAutocompleteFilter alloc] init];
filter.locationBias = GMSPlaceCircularLocationOption(center, radius);
GMSAutocompleteRequest *request = [[GMSAutocompleteRequest alloc] initWithQuery:@"Sicilian piz"];
request.sessionToken = token;
request.filter = filter;

[[GMSPlacesClient sharedClient] fetchAutocompleteSuggestionsFromRequest:request callback:^(NSArray<GMSAutocompleteSuggestion *> * results, NSError * error){
  // Handle response
  for (GMSAutocompleteSuggestion *suggestion in results) {
    if (suggestion.placeSuggestion) {
      // Show place suggestion data.
    }
  }
}];

Places Swift SDK for iOS(预览版)

let center = (37.775061, -122.419400)
let radius = 5000.0
let bias = CircularCoordinateRegion(center: center, radius: radius)
let filter = AutocompleteFilter(coordinateRegionBias: bias)
let token = AutocompleteSessionToken()

let autocompleteRequest = AutocompleteRequest(query: "Sicilian piz", sessionToken: token, filter: filter)
switch await placesClient.fetchAutocompleteSuggestions(with: autocompleteRequest) {
case .success(let autocompleteSuggestions):
  for suggestion in autocompleteSuggestions {
    switch suggestion {
    case .place:
      // Show place suggestion data.
    }
  }
case .failure(let placesError):
  // Handle error.
}
  

使用类型

使用 types 参数可将请求的结果限制为表格 A表格 B 中列出的特定类型。您最多可以指定包含五个值的数组。如果省略,则返回所有类型。

以下示例指定了“Soccer”查询字符串,并使用 types 参数将结果限制为类型为 "sporting_goods_store" 的场所:

Swift

let token = GMSAutocompleteSessionToken()

let filter = GMSAutocompleteFilter()
filter.types = ["sporting_goods_store"]
    
let request = GMSAutocompleteRequest(query:"Soccer")
request.filter = filter
request.sessionToken = token

GMSPlacesClient.shared().fetchAutocompleteSuggestions(from: request, callback: { ( results, error ) in
      if let error = error {
        print("Autocomplete error: \(error)")
        return
      }
      if let autocompleteResults = results {
        for result in autocompleteResults {
          print("Result \(String(describing: result.placeSuggestion?.placeID)) with \(String(describing: result.placeSuggestion?.attributedFullText))")
        }
      }
    })

Objective-C

GMSAutocompleteFilter *filter = [[GMSAutocompleteFilter alloc] init];
filter.types = @[ "sporting_goods_store" ];
GMSAutocompleteRequest *request = [[GMSAutocompleteRequest alloc] initWithQuery:@"Soccer"];
request.sessionToken = token;
request.filter = filter;

[[GMSPlacesClient sharedClient] fetchAutocompleteSuggestionsFromRequest:request callback:^(NSArray<GMSAutocompleteSuggestion *> * results, NSError * error){
  // Handle response
  for (GMSAutocompleteSuggestion *suggestion in results) {
    if (suggestion.placeSuggestion) {
      // Show place suggestion data.
    }
  }
}];

Places Swift SDK for iOS(预览版)

let filter = AutocompleteFilter(types: [ PlaceType(rawValue: "sporting_goods_store") ])
let token = AutocompleteSessionToken()

let autocompleteRequest = AutocompleteRequest(query: "Soccer", sessionToken: token, filter: filter)
switch await placesClient.fetchAutocompleteSuggestions(with: autocompleteRequest) {
case .success(let autocompleteSuggestions):
  for suggestion in autocompleteSuggestions {
    switch suggestion {
    case .place:
      // Show place suggestion data.
    }
  }
case .failure(let placesError):
  // Handle error.
}
    

使用来源

当您在请求中添加 origin 参数(指定为经纬度坐标)时,API 会在响应中包含从起点到终点的直线距离。响应会将距离返回为 distanceMeters

以下示例将原点设置为旧金山市中心:

Swift

let token = GMSAutocompleteSessionToken()

let origin = CLLocation(latitude: 37.7749, longitude: -122.4194)

let filter = GMSAutocompleteFilter()

filter.origin =  origin
    
let request = GMSAutocompleteRequest(query:"Amoeba")
request.filter = filter
request.sessionToken = token

GMSPlacesClient.shared().fetchAutocompleteSuggestions(from: request, callback: { ( results, error ) in
      if let error = error {
        print("Autocomplete error: \(error)")
        return
      }
      if let autocompleteResults = results {
        for result in autocompleteResults {
          print("Result \(String(describing: result.placeSuggestion?.placeID)) with \(String(describing: result.placeSuggestion?.attributedFullText)) and distance: \(String(describing: result.placeSuggestion?.distanceMeters))")
        }
      }
    })

Objective-C

GMSAutocompleteFilter *filter = [[GMSAutocompleteFilter alloc] init];
filter.origin = [[CLLocation alloc] initWithLatitude:37.395804 longitude:-122.077023];
GMSAutocompleteRequest *request = [[GMSAutocompleteRequest alloc] initWithQuery:@"Amoeba"];
request.sessionToken = token;
request.filter = filter;

[[GMSPlacesClient sharedClient] fetchAutocompleteSuggestionsFromRequest:request callback:^(NSArray<GMSAutocompleteSuggestion *> * results, NSError * error){
  // Handle response
  for (GMSAutocompleteSuggestion *suggestion in results) {
    if (suggestion.placeSuggestion) {
      // Show place suggestion data.
      }
    }
}];

Places Swift SDK for iOS(预览版)

let filter = AutocompleteFilter(origin: CLLocation(latitude: 37.7749, longitude: -122.4194))
let token = AutocompleteSessionToken()

let autocompleteRequest = AutocompleteRequest(query: "Amoeba", sessionToken: token, filter: filter)
switch await placesClient.fetchAutocompleteSuggestions(with: autocompleteRequest) {
case .success(let autocompleteSuggestions):
  for suggestion in autocompleteSuggestions {
    switch suggestion {
    case .place:
      // Show place suggestion data.
    }
  }
case .failure(let placesError):
  // Handle error.
}
  

归因

即使没有地图,您也可以使用“自动补全(新)”功能。如果您确实要显示地图,则必须使用 Google 地图。当您选择不在地图上显示自动补全(新)服务提供的建议时,则必须在搜索字段/结果中显示 Google 徽标。如需了解详情,请参阅显示 Google 徽标和归属信息