ios 如何使用 Apple Map Kit 实现地址自动完成
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33380711/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to implement auto-complete for address using Apple Map Kit
提问by Mostafa Mohamed Raafat
I want to auto-complete the address for the user as same as what google api provides in this link:
我想自动完成用户的地址,就像 google api 在此链接中提供的一样:
https://developers.google.com/maps/documentation/javascript/places-autocomplete?hl=en
https://developers.google.com/maps/documentation/javascript/places-autocomplete?hl=en
How can i implement the same functionality using apple map kit?
如何使用苹果地图套件实现相同的功能?
I have tried to use the Geo Coder, i wrote this for example:
我曾尝试使用地理编码器,例如我写的:
@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)
}
}
}
}
However the results are very disappointing.
然而,结果非常令人失望。
Any Apple APIs available to implement such functionality, or should i head for google api ?
任何可用于实现此类功能的 Apple API,还是我应该使用 google api?
Thank you
谢谢
回答by George McDonnell
Update - I've created a simple example project hereusing Swift 3 as the original answer was written in Swift 2.
更新 - 我在这里使用 Swift 3创建了一个简单的示例项目,因为原始答案是用 Swift 2 编写的。
In iOS 9.3 a new class called MKLocalSearchCompleter
was introduced, this allows the creation of an autocomplete solution, you simply pass in the queryFragment as below:
在 iOS 9.3MKLocalSearchCompleter
中引入了一个名为的新类,这允许创建自动完成解决方案,您只需按如下方式传入 queryFragment:
var searchCompleter = MKLocalSearchCompleter()
searchCompleter.delegate = self
var searchResults = [MKLocalSearchCompletion]()
searchCompleter.queryFragment = searchField.text!
Then handle the results of the query using the MKLocalSearchCompleterDelegate
:
然后使用以下命令处理查询结果MKLocalSearchCompleterDelegate
:
extension SearchViewController: MKLocalSearchCompleterDelegate {
func completerDidUpdateResults(completer: MKLocalSearchCompleter) {
searchResults = completer.results
searchResultsTableView.reloadData()
}
func completer(completer: MKLocalSearchCompleter, didFailWithError error: NSError) {
// handle error
}
}
And display the address results in an appropriate format:
并以适当的格式显示地址结果:
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
}
You can then use a MKLocalCompletion
object to instantiate a MKLocalSearch.Request
, thus gaining access to the MKPlacemark
and all other useful data:
然后您可以使用一个MKLocalCompletion
对象来实例化 a 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
}
}
回答by Gogi
My answer is fully based on @George McDonnell's. I hope it helps to guys who has troubles with implementing of the last one.
我的回答完全基于@George McDonnell's。我希望它对那些在实施最后一个方面有困难的人有所帮助。
import UIKit
import MapKit
class ViewController: UIViewController {
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var tableVIew: UITableView!
//create a completer
lazy var searchCompleter: MKLocalSearchCompleter = {
let sC = MKLocalSearchCompleter()
sC.delegate = self
return sC
}()
var searchSource: [String]?
}
extension ViewController: UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
//change searchCompleter depends on searchBar's text
if !searchText.isEmpty {
searchCompleter.queryFragment = searchText
}
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return searchSource?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//I've created SearchCell beforehand; it might be your cell type
let cell = self.tableVIew.dequeueReusableCell(withIdentifier: "SearchCell", for: indexPath) as! SearchCell
cell.label.text = self.searchSource?[indexPath.row]
// + " " + searchResult.subtitle
return cell
}
}
extension ViewController: MKLocalSearchCompleterDelegate {
func completerDidUpdateResults(_ completer: MKLocalSearchCompleter) {
//get result, transform it to our needs and fill our dataSource
self.searchSource = completer.results.map { ##代码##.title }
DispatchQueue.main.async {
self.tableVIew.reloadData()
}
}
func completer(_ completer: MKLocalSearchCompleter, didFailWithError error: Error) {
//handle the error
print(error.localizedDescription)
}
}
回答by Apekshit
SAMPLE PROJECT FOR THIS ISSUE CAN BE DOWNLOAD FROM HERE
可以从这里下载本期的示例项目
In this sample project this issue is achieved through MKLocalSearchRequest and MapKit.
在这个示例项目中,这个问题是通过 MKLocalSearchRequest 和 MapKit 实现的。
It is showing autocomplete places just like google places API and can place the Annotation point on Apple's map (not on Google map, I hope that is only you are looking for.)
它像谷歌地点 API 一样显示自动完成的地点,并且可以将注释点放在 Apple 的地图上(不是在谷歌地图上,我希望这只是你正在寻找的。)
However it does not show as accurate result as you can get from Google Places API. As the problem is that Geocoding database is not obviously complete and Apple is not the company who leads this field - Google is.
但是,它显示的结果不如您从 Google Places API 获得的准确。问题是地理编码数据库显然不完整,而且苹果不是领导这个领域的公司——谷歌才是。
Attaching some screenshots of the sample app, so you can see if it is useful for your requirement or not.
附上示例应用程序的一些屏幕截图,以便您查看它是否对您的要求有用。
Hope this is what you are looking for!
希望这就是你要找的!