Place Autocomplete (新版)

Autocomplete (新版) 服務是 iOS API,可根據要求傳回地點建議。在要求中指定文字搜尋字串和地理範圍,以便控制搜尋範圍。

Autocomplete (New) 服務可比對輸入內容的完整字詞和子字串,解析地點名稱、地址和 Plus Codes。因此,應用程式可在使用者輸入內容時傳送查詢,即時提供地點建議。

地點建議是根據指定的輸入文字字串和搜尋區域,提供的商家、地址和搜尋點等地點。

舉例來說,您可以使用包含部分使用者輸入內容「Spagh」的字串做為輸入內容,並將搜尋範圍限制在紐約市,來呼叫 API。回應會包含與搜尋字串和搜尋區域相符的地點建議清單,例如名為「Cafe Spaghetti」的餐廳,以及該地點的詳細資料。

系統會將傳回的地點建議呈現給使用者,方便他們選取所需地點。您可以提出 Place Details (新版) 要求,進一步瞭解任何傳回的地點建議。

Autocomplete (New) 要求

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.
    }
  }
}];

iOS 版 Places Swift SDK (預覽版)

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.
}

Autocomplete (New) 回覆

自動完成功能會傳回最多五個 GMSAutocompleteSuggestion 例項的陣列。陣列包含:

  • placeID
  • types:適用於此地點的類型。
  • distanceMeters:與原點的距離。
  • attributedFullText:建議的完整人類可讀文字。
  • attributedPrimaryText:建議內容的主要文字,可供使用者閱讀。
  • attributedSecondaryText:建議內容的輔助文字,方便使用者閱讀。
  • structuredFormat:特定名稱和不含歧義的文字,例如城市或區域。

必要參數

查詢

要搜尋的文字字串。指定完整字詞和子字串、地點名稱、地址和 Plus Codes。Autocomplete (New) 服務會根據這個字串傳回候選相符項目,並依據觀察到的關聯性排序結果。

選用參數

類型

地點只能有一個單一主要類型,來自與其相關聯的 Table ATable 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" ];

iOS 版 Places Swift SDK (預覽版)

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);

iOS 版 Places Swift SDK (預覽版)

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);

iOS 版 Places Swift SDK (預覽版)

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];

iOS 版 Places Swift SDK (預覽版)

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

regionCode

用於格式化回應的區碼,採 ccTLD (「頂層網域」) 的兩位字元值 大多數 ccTLD 代碼與 ISO 3166-1 代碼相同,但有一些需要注意的例外情況。舉例來說,英國的 ccTLD 是「uk」(.co.uk),而 ISO 3166-1 代碼是「gb」(技術上代表「大不列顛與北愛爾蘭聯合王國」實體)。

如果您指定無效的區域代碼,API 會傳回 INVALID_ARGUMENT 錯誤。這個參數可能會影響根據適用法律產生的結果。

sessionToken

工作階段符記是使用者產生的字串,可追蹤 Autocomplete (New) 呼叫的「工作階段」。Autocomplete (New) 會使用工作階段符記,將使用者自動完成搜尋的查詢和選取階段歸入不同的工作階段,以用於計費。詳情請參閱「工作階段符記」。

自動完成 (新版) 範例

使用 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.
    }
  }
}];

iOS 版 Places Swift SDK (預覽版)

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.
    }
  }
}];

iOS 版 Places Swift SDK (預覽版)

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 所列的特定類型。您最多可以指定五個值的陣列。如果省略,系統會傳回所有類型。

以下範例會指定「足球」的查詢字串,並使用 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.
    }
  }
}];

iOS 版 Places Swift SDK (預覽版)

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.
      }
    }
}];

iOS 版 Places Swift SDK (預覽版)

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.
}
  

歸因

即使沒有地圖,您也可以使用 Autocomplete (New)。如要顯示地圖,則必須使用 Google 地圖。如果您要顯示自動完成 (新版) 服務的建議,但不顯示地圖,則必須在搜尋欄位/結果中顯示 Google 標誌。詳情請參閱「顯示 Google 標誌和歸屬資訊」。