2014-04-19 53 views
4

我正在開發一個應用程序,用戶可以在其中搜索興趣點,選擇搜索結果,然後MKMapView將以結果座標爲中心。如何使用自動完成和建議使用UISearchBar搜索位置?

我的問題是,如何讓自動完成發生?我對MKLocalSearchMKLocalSearchRequest進行了研究,似乎蘋果公司在iOS6.1 +上爲位置搜索建議了API。不過,我找不到任何自動完成或與MKLocalSearchMKLocalSearchRequest建議的例子。是否可以自動完成位置搜索或顯示與Apple地圖應用程序相似的建議列表?謝謝!

+1

,如果你想加入谷歌位置意味着再有就是像下面http://maps.googleapis.com/maps/api/geocode/json?address=%@&sensor=true和位置搜索的免費API你也可以在UITableView中列出它們,當用戶點擊一個單元格時,你可以動態地將它添加到SearchBox中。 –

回答

6

檢查這個帖子:https://stackoverflow.com/a/20141677/1464327

基本上,你可以讓多個請求。例如,當用戶鍵入時,啓動計時器,當計時器結束時,發出請求。每當用戶輸入時,取消前一個定時器。

實現文本字段委託textField:shouldChangeCharactersInRange:replacementString:

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

然後執行_search方法發出請求。

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 
}]; 

我從來沒有實現過這樣的東西。我只是告訴我的出發點是什麼。希望這會給你一些方向。

+1

也許最好使用'performSelector:withObject:afterDelay:'而不是'NSTimer'。 http://stackoverflow.com/a/7061472/242933 – ma11hew28

相關問題