如何在MKMapView中使用MKLocalSearch

How to use MKLocalSearch In MKMapView

我在 MKMapView 中使用 MKLocalSearch..我的实现如下

extension MYClass: SendLocationDelegate{

    func sendCoOrdinates(loccoordinate:CLLocation, placemark:CLPlacemark){

        println(" Google VC coordinate is as \(loccoordinate.coordinate.longitude) \(loccoordinate.coordinate.latitude)")
        let location:CLLocationCoordinate2D = CLLocationCoordinate2D(latitude:loccoordinate.coordinate.latitude, longitude: loccoordinate.coordinate.longitude)
        let theSpan : MKCoordinateSpan = MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta:0.01)
        let theRegion : MKCoordinateRegion = MKCoordinateRegion(center: location, span: theSpan)
        self.mapView.setRegion(theRegion, animated: false)

        let request = MKLocalSearchRequest()
        request.region = mapView.region
        let search = MKLocalSearch(request: request)

        search.startWithCompletionHandler({(response: MKLocalSearchResponse!,
            error: NSError!) in

            if error != nil {
                println("Error occured in search: \(error.localizedDescription)")

            } else if response.mapItems.count == 0 {

                println("No matches found")

            } else {

                println("Matches found")

                println("\(response)")

            }
        })



    }


}

输出:Google VC 坐标为 72.8561644 19.0176147 搜索时出错:操作无法完成。 (MKErrorDomain 错误 1。) 为什么会这样?

已编辑:但是当我将请求更改为

let request = MKLocalSearchRequest()
 request.naturalLanguageQuery = "india"
 //request.region = mapView.region
 let search = MKLocalSearch(request: request)

我得到了很好的回应

{ boundingRegion = ""; mapItems = ( " {\n isCurrentLocation = 0;\n name = India;\n placemark = \"India, India @ <+23.04117260,+78.89180550> +/- 0.00m, region CLCircularRegion (identifier:'<+21.84329084,+82.78786665> radius 2237301.34', center:<+21.84329084,+82.78786665>, radius:2237301.34m)\";\n}" ); }

一切正常..只是你在不包含自然语言查询的请求上犯了一个错误

 let request = MKLocalSearchRequest()
 request.region = mapView.region
 let search = MKLocalSearch(request: request)

在这种情况下 request.naturalLanguageQuery 将其设置为 nil....因此您在 Apple 文档 herenaturalLanguageQuery 上得到了未知 type.Look 的(MKErrorDomain 错误 1)不能包含 nil 值...所以用它提出请求

let request = MKLocalSearchRequest()
 request.naturalLanguageQuery = "india"
 let search = MKLocalSearch(request: request)

您可以使用region参数将搜索结果列表缩小到指定区域内或附近的搜索结果。指定一个区域并不能保证结果都在该区域内。它只是对搜索引擎的提示。所以 region 在这里可以作为可选的。或者您可以提出要求以获得更好的结果

let request = MKLocalSearchRequest()
request.naturalLanguageQuery = "india"
request.region = mapView.region
let search = MKLocalSearch(request: request)