我有一个mapview,我添加了一个方法来在用户按下的位置放置一个图钉。标注显示图像上显示的位置地址。
screenshot of my mapview with annotation pin and callout view.
我的代码如下:
func onTapGestureRecognized(sender: UILongPressGestureRecognizer) {
self.mapView.removeAnnotations(mapView.annotations)
let location = tapRecognizer.location(in: mapView)
let coordinate = mapView.convert(location,toCoordinateFrom: mapView)
let getLat: CLLocationDegrees = coordinate.latitude
let getLon: CLLocationDegrees = coordinate.longitude
let theLocation: CLLocation = CLLocation(latitude: getLat, longitude: getLon)
let geoCoder = CLGeocoder()
geoCoder.reverseGeocodeLocation(theLocation, completionHandler: { (placemarks, error) -> Void in
// Place details
var placeMark: CLPlacemark!
placeMark = placemarks?[0]
var theLocationName = ""
var theStreetNumber = ""
var theStreet = ""
var theCity = ""
var theZip = ""
var theCountry = ""
// Address dictionary
print(placeMark.addressDictionary as Any)
// Location name
if let locationName = placeMark.name{
theLocationName = locationName
}
if let streetNumber = placeMark.subThoroughfare{
theStreetNumber = streetNumber
}
// Street address
if let street = placeMark.thoroughfare {
theStreet = street
}
// City
if let city = placeMark.locality {
theCity = city
}
// Zip code
if let zip = placeMark.postalCode{
theZip = zip
}
// Country
if let country = placeMark.isoCountryCode{
theCountry = country
}
let annotation = MKPointAnnotation()
annotation.title = theLocationName
annotation.subtitle = theStreetNumber + " " + theStreet + ", " + theCity + ", " + theCountry + ", " + theZip
if let location = placeMark.location {
annotation.coordinate = location.coordinate
// Display the annotation
self.mapView.showAnnotations([annotation], animated: true)
}
})
}
正如你所看到的,当我试图通过调用行来获取位置名称(((如果让locationName = placeMark.name)))),我只能得到地址:“5197 Yonge St”,而不是餐厅名称:“Pho 88 Restaurant”。
谁能告诉我哪里做错了?或者它根本无法实现?谢谢!
答案 0 :(得分:0)
我不能给你一个完整的答案,但我可以指出你正确的方向。据我所见,您只会为placemarks
返回一个条目,但可以使用MKLocalSearchRequest
获取更完整的列表。挑战在于如何将返回的值与您想要的值完全匹配 - 也许您必须要求用户从短列表中进行选择?此外,我认为您需要指定您要搜索的机构类型。您可以在上面的完成处理程序中包含以下内容
let request = MKLocalSearchRequest()
request.naturalLanguageQuery = "restaurant" // or whatever you're searching for
request.region = MKCoordinateRegion(center: CLLocationCoordinate2D(latitude: getLat, longitude: getLon), span: self.mapView.region.span)
let search = MKLocalSearch(request: request)
search.start { response, error in
guard let response = response else {
print("There was an error searching for: \(request.naturalLanguageQuery) error: \(error)")
return
}
print("There are \(response.mapItems.count)")
for item in response.mapItems {
// You may be able to match the address to what the geoCode gives you
// or present the user with a list of options
print("\(item.name), \(item.placemark)")
}
}
当我对此进行测试时,地址并不总是匹配,即使放大也是如此 - 因此当geoCoder
在1-3 Some Street
返回一家餐馆时,MKLocalSearchRequest
可能会给我3 Some Street
{1}}