是否可以在不提供naturalLanguageQuery的情况下使用MKLocalSearchRequest显示附近的位置?
我知道典型的方法是使用foursquare或谷歌。两者我都用过
我已经尝试实现这一点一段时间了,但最接近的是使用for循环运行多个查询并将结果添加到主数组。效率低下,你有更多的成功吗?
您可以实现以下演示目的,但我不建议在生产应用程序中使用这种方法,因为它显然是不可伸缩的。
var nearbyPlaces: [MKMapItem] = []
let params: [String] = ["bar", "shop", "restaurant", "cinema"]
let request = MKLocalSearchRequest()
let span = MKCoordinateSpan(latitudeDelta: CLLocationDegrees(exactly: 1000)!, longitudeDelta: CLLocationDegrees(exactly: 1000)!)
let region = MKCoordinateRegion(center: coord, span: span)
request.region = region
for param in params {
request.naturalLanguageQuery = param
let places = MKLocalSearch(request: request)
places.start { [unowned self] response, error in
guard let result = response else { return }
self.nearbyPlaces.append(contentsOf: result.mapItems)
}
}
我的策略是
- 使用地理编码获取一个位置标记
- 生成一个看起来不错的搜索文本(我对此没有信心)
- 请求MKLocalSearch
伪代码在这里。
func placemark() async throws -> CLPlacemark? {
// (1)
let geocoder: CLGeocoder = .init()
let location: CLLocation = .init(
latitude: coordinate.latitude,
longitude: coordinate.longitude
)
return try await geocoder.reverseGeocodeLocation(location).first
}
func findNearbyMapItems() async {
guard let placemark = placemark else {
return
}
// (2)
let searchText: String = Array(Set([
placemark.administrativeArea ?? "",
placemark.subAdministrativeArea ?? "",
placemark.locality ?? "",
])).joined(separator: " ").trimmingCharacters(in: .whitespacesAndNewlines)
// (3)
let nearbyMeters: CLLocationDistance = 500
let request = MKLocalSearch.Request()
request.naturalLanguageQuery = searchText
request.resultTypes = [.pointOfInterest]
request.region = MKCoordinateRegion(
center: center,
latitudinalMeters: nearbyMeters,
longitudinalMeters: nearbyMeters
)
let response = try await MKLocalSearch(request: request).start()
return response.mapItems
}
另一种解决方案仅适用于POI。
func mapItemsNearbyPOIOnSystem(radius: CLLocationDistance = 500) async throws -> [MKMapItem] {
let request: MKLocalPointsOfInterestRequest = .init(center: coordinate, radius: radius)
let response = try await MKLocalSearch(request: request).start()
return response.mapItems
}