Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 465
wz366 Avatar asked Mar 19 '23 20:03

wz366


1 Answers

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.

like image 77
rtiago42 Avatar answered Mar 22 '23 13:03

rtiago42