wz366
wz366

Reputation: 2930

How to search for locations using UISearchBar with autocompletion and suggestions?

I am developing an app in which user can search for a point of interests, pick a search result and then the MKMapView will be centered to the result coordinate.

My question is how to make autocompletion happen? I have did research on MKLocalSearch and MKLocalSearchRequest, and it seems that is Apple suggested API for location search on iOS6.1+. However I cannot find any examples with autocompletion or suggestions with MKLocalSearch and MKLocalSearchRequest. Is it possible to autocomplete a location search or display a list of suggestions just like Apple's Maps app? Thanks!

Upvotes: 4

Views: 6059

Answers (1)

rtiago42
rtiago42

Reputation: 572

Check this post: https://stackoverflow.com/a/20141677/1464327

Basically, you can make multiple requests. For exemple, when the user types, start a timer, when the timer finishes, make a request. Whenever the user types, cancel the previous timer.

Implement textField:shouldChangeCharactersInRange:replacementString: of the text field delegate.

static NSTimer *_timer = nil;
[_timer invalidate];
_timer = [NSTimer timerWithTimeInterval:1.5 target:self selector:@selector(_search:) userInfo:nil repeats:NO];

Then implement the _search method to make the request.

MKLocalSearchRequest *request = [[MKLocalSearchRequest alloc] init];
request.region = regionToSearchIn;
request.naturalLanguageQuery = self.textField.text;
MKLocalSearch *localSearch = [[MKLocalSearch alloc] initWithRequest:request];
[localSearch startWithCompletionHandler:^(MKLocalSearchResponse *response, NSError *error) {
    // check for error and process the response
}];

I've never implemented something like this. I'm just telling what my starting point would be. Hopefully this will give you some direction.

Upvotes: 7

Related Questions