ios MKLocalsearchRequest附近的地方而无需naturalLanguageQuery字符串

kzipqqlq  于 2023-01-10  发布在  iOS
关注(0)|答案(3)|浏览(311)

是否可以在不提供naturalLanguageQuery的情况下使用MKLocalSearchRequest显示附近的地点?

我知道通常的做法是使用Foursquare或Google,我两个都用过。

rbl8hiat

rbl8hiat1#

我已经尝试了一段时间来实现这一点,但最接近我来是使用一个for循环运行多个查询,并添加结果到主数组.令人难以置信的效率显然,你有更多的成功?

4xrmg8kj

4xrmg8kj2#

您可以通过以下方式实现演示目的,但我建议在生产应用程序中使用这种方法,因为它显然不可扩展。

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)
        }

}
jqjz2hbq

jqjz2hbq3#

我的策略是
1.使用地理编码器获取地标。
1.生成一个看起来不错的搜索文本(我对此没有信心)。
1.请求MK本地搜索。
伪代码在这里。

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
}

相关问题