Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift is it possible to set a specific country for MKLocalSearchRequest and MKLocalSearchResponse

I wonder if its possible to set a country for MKLocalSearchRequest and MKLocalSearchResponse in mapKit?

In my map view the user can search for a zip/state. But I don't want to show hits in other countries since it would not make any sense here.

Thanks in advance,

localSearchRequest = MKLocalSearchRequest()
        localSearchRequest.naturalLanguageQuery = "23138"
        localSearch = MKLocalSearch(request: localSearchRequest)
        localSearch.startWithCompletionHandler { (localSearchResponse, error) -> Void in



            if localSearchResponse == nil || self.mapView == nil{
                var alert = UIAlertView(title: nil, message: "Place not found", delegate: self, cancelButtonTitle: "Try again")
                alert.show()
                return
            } else {

                let location = CLLocationCoordinate2D(latitude: localSearchResponse.boundingRegion.center.latitude, longitude:     localSearchResponse.boundingRegion.center.longitude)


                let span = MKCoordinateSpanMake(0.05, 0.05)
                let region = MKCoordinateRegion(center: location, span: span)
                self.mapView.setRegion(region, animated: false)


                self.pointAnnotation = MKPointAnnotation()
                self.pointAnnotation.coordinate = location
                self.mapView.addAnnotation(self.pointAnnotation)
            }


        }
like image 523
Kiwo Tew Avatar asked Dec 20 '22 01:12

Kiwo Tew


1 Answers

While there doesn't appear to be a way to explicitly constrain an MKLocalSearchRequest to a specific geographic context, you can get pretty close with the following steps:

  1. Set the search request's region property to an MKCoordinateRegion corresponding to the USA (unfortunately, Alaska and Hawaii make the region rather large; depending on your application, you may want to use just the continental USA).
  2. In your callback handler, you can filter the MKMapItem array returned from the MKLocalSearchResponse by their placemark properties' countryCode property, to only use those whose country code is "US".

If you're not getting the kind of results you'd like, you can investigate other third-party API services, to see if any of those would be more suitable for your specific use case.

like image 159
mattt Avatar answered Dec 24 '22 01:12

mattt