4

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!

wz366
  • 2,840
  • 6
  • 25
  • 34
  • 1
    if you like to add the Google location means then there is an free API for location Search like the following http://maps.googleapis.com/maps/api/geocode/json?address=%@&sensor=true and also you can list them out in a UITableView and when user click's an cell you can dynamically add it into the SearchBox. – Prabhu Natarajan Apr 28 '14 at 07:08

1 Answers1

7

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.

Community
  • 1
  • 1
rtiago42
  • 572
  • 3
  • 9
  • 1
    Perhaps it's better to use `performSelector:withObject:afterDelay:` than `NSTimer`. http://stackoverflow.com/a/7061472/242933 – ma11hew28 Aug 29 '14 at 15:52
  • Just FYI for anyone else, UISearchBarDelegate has it's own method for [`searchBar:shouldChangeTextInRange:replacementText`](https://developer.apple.com/documentation/uikit/uisearchbardelegate/1624328-searchbar?language=objc). – Michael Dautermann May 29 '18 at 05:50