我有城市名称,即德克萨斯州奥斯汀。在搜索场所时,我需要使用该城市作为边界参数。知道怎么做吗?
let filter = GMSAutocompleteFilter()
filter.type = .establishment
placesClient.autocompleteQuery(textField.text!, bounds: nil, filter: filter, callback: {(results, error) -> Void in
if let error = error {
print("Autocomplete error \(error)")
return
}
if let results = results {
print(results)
}
})
答案 0 :(得分:1)
我没有使用GMSAutocompleteFilter,但我已经使用google api实现了,所以我在这里分享一些示例代码,试试这个:
带上搜索栏&实施其代表和如下调用谷歌放置api。在这里,您需要传递城市名称。所以在调用此api之后,您将获得结果。有了这个结果,我将地名存储在两个不同的字符串中,即strMainTitle& strSubTitle。最后重新加载表到显示列表。你还必须实现tableview delegate&用于在表上显示列表的数据源方法。(这里需要使用tableview来显示搜索文本查询)。
// MARK:- SearchBar Delegate methods
func searchBar(searchBar: UISearchBar,textDidChange searchText: String)
{
let strCityString = "your city name"
let session = NSURLSession.sharedSession()
let apiServerKey = "Put here your apiServerkey"
var urlString = "https://maps.googleapis.com/maps/api/place/autocomplete/json?key=\(apiServerKey)&input=\(strCityString)"+"\(searchBarObj.text!)"
urlString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
session.dataTaskWithURL(NSURL(string: urlString)!) {
(data, response, error) -> Void in
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options:[]) as? [String:AnyObject] {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let returnedPlaces: NSArray? = json["predictions"] as? NSArray// print("Predictions Retrunedplaces: \(returnedPlaces)")
self.arraySearchResults.removeAllObjects()
self.arraySearchResults.addObjectsFromArray(json["predictions"] as! [AnyObject])// (returnedPlaces!)
self.strMainTitle.removeAllObjects()
self.strSubTitle.removeAllObjects()
for index in 0..<returnedPlaces!.count {
if let returnedPlace = returnedPlaces?[index] as? NSDictionary {
var placeName = ""
if let name = returnedPlace["description"] as? NSString {
placeName = name as String
}
var fullNameArr = placeName.componentsSeparatedByString(",")
var strname = String()
let laststring:Int = fullNameArr.count - 1
for i in 1..<fullNameArr.count
{
if i == laststring //fullNameArr.count - 1
{
strname += "\(fullNameArr[i])"
}
else
{
strname += "\(fullNameArr[i])"+","
}
}
self.strMainTitle.addObject(placeName.componentsSeparatedByString(",").first!)
self.strSubTitle.addObject(strname)
}
}
self.tableviewForSearchBar.reloadData()
})
}
} catch {
}
}.resume()
}