MKLocalSearch Example

Apple released iOS 6.1 today and one of the new developer features is access to the built in MKMapKit search api, better know as MKLocalSearch (docs). Accessing the search api allows you to use Apple Maps’s natural language searching to look for and display locations within your own app (though we all know how the initial Map launch went so depending on your area the quality of the results may vary).

To demonstrate the functionality, I’ve created a quick Git repo that shows MKLocalSearch in action. Feel free to download it an play.

The basic usage requires you to set up an MKLocalSearchRequest that contains a search region and the natural language query:

MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];
request.naturalLanguageQuery = searchBar.text;
request.region = self.ibMapView.region;

For demonstration purposes, my region is defined by the visible MKMapView (from the Interface Builder storyboard) and the natural language query is whatever you type into the search bar. This way you can experiment with search terms.

The MKLocalSearchRequest is then used to create an instance of MKLocalSearch. The search uses a block completion handler to return an MKLocalSearchResponse object with and array of MKItems:

[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
localSearch = [[MKLocalSearch alloc] initWithRequest:request];

[localSearch startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error){

	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

	if (error != nil) {
		[[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Map Error",nil)
									message:[error localizedDescription]
						  cancelButtonTitle:NSLocalizedString(@"OK",nil) otherButtonTitles:nil] show];
	if ([response.mapItems count] == 0) {
		[[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"No Results",nil)
						  cancelButtonTitle:NSLocalizedString(@"OK",nil) otherButtonTitles:nil] show];

	results = response;
	[self.searchDisplayController.searchResultsTableView reloadData];

In the demo I’m simply storing the response and using it to display the MKItems in the search display controller’s results table.

The guts of the example is in ViewController.m so start there.