我想自动填写用户的地址,就像该链接中google api提供的地址一样:
https://developers.google.com/maps/documentation/javascript/places- autocomplete?hl=zh- CN
如何使用Apple Map Kit实施相同的功能?
我尝试使用地理编码器,例如,我这样写:
@IBAction func SubmitGeoCode(sender: AnyObject) { let address = "1 Mart" let coder = CLGeocoder() coder.geocodeAddressString(address) { (placemarks, error) -> Void in for placemark in placemarks! { let lines = placemark.addressDictionary?["FormattedAddressLines"] as? [String] for addressline in lines! { print(addressline) } } } }
但是结果非常令人失望。
任何可用于实现此类功能的Apple API,还是我应该使用Google API?
谢谢
更新-我在 这里使用Swift 3 创建了一个简单的示例项目,因为原始答案是使用Swift 2编写的。
在iOS 9.3中MKLocalSearchCompleter,引入了一个新类,该类允许创建自动完成解决方案,您只需将queryFragment传递如下:
MKLocalSearchCompleter
var searchCompleter = MKLocalSearchCompleter() searchCompleter.delegate = self var searchResults = [MKLocalSearchCompletion]() searchCompleter.queryFragment = searchField.text!
然后使用来处理查询结果MKLocalSearchCompleterDelegate:
MKLocalSearchCompleterDelegate
extension SearchViewController: MKLocalSearchCompleterDelegate { func completerDidUpdateResults(completer: MKLocalSearchCompleter) { searchResults = completer.results searchResultsTableView.reloadData() } func completer(completer: MKLocalSearchCompleter, didFailWithError error: NSError) { // handle error } }
并以适当的格式显示地址结果:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let searchResult = searchResults[indexPath.row] let cell = UITableViewCell(style: .subtitle, reuseIdentifier: nil) cell.textLabel?.text = searchResult.title cell.detailTextLabel?.text = searchResult.subtitle return cell }
然后,您可以使用MKLocalCompletion对象实例化MKLocalSearch.Request,从而获得对MKPlacemark和所有其他有用数据的访问:
MKLocalCompletion
MKLocalSearch.Request
MKPlacemark
let searchRequest = MKLocalSearch.Request(completion: completion!) let search = MKLocalSearch(request: searchRequest) search.startWithCompletionHandler { (response, error) in if error == nil { let coordinate = response?.mapItems[0].placemark.coordinate } }