2015-10-17 62 views
0

即時建立一個應用程序在IOS中,它有一個UITextView用戶輸入類似他的地址,但沒有整個,谷歌應該預測並完成地址,我已經有一個谷歌的鑰匙,請幫我執行這一點,我無法理解如何如何在UitextView中集成谷歌地點搜索器?

+0

[如何設置谷歌將自動完成請求置於iOS中的UITextField](http://stackoverflow.com/questions/13005494/how-to-set-the-google-places-autocomplete -requests-to-a-uitextfield-in-ios) –

+0

或者你也可以使用這個https://github.com/mrugrajsinh/MVAutocompletePlaceSearchTextField –

回答

0

首先,您必須從- (void)textViewDidChange:(UITextView *)textView委託方法獲取更新文本。然後使用谷歌地圖SDK搜索最匹配的位置。

- (void)textViewDidChange:(UITextView *)textView { 
    [self searchLocationWithText:textView.text]; 
} 

- (void)searchLocationWithText:(NSString *)searchText 
{ 
    NSString *url = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/textsearch/json?query=%@&key=%@", searchText, kGoogleSDKBrowserKey]; 
    NSURL *googleRequestURL = [NSURL URLWithString:url]; 
    // Retrieve the results of the URL. 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
      NSData *data = [NSData dataWithContentsOfURL:googleRequestURL]; 
      NSError *error = nil; 
      NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; 

      if ([[json objectForKey:@"status"] isEqualToString:@"OK"]) { 
       NSArray *locations = [json objectForKey:@"results"]; 
       NSDictionary *place = [locations firstObject]; 
       NSString *locationName = [place objectForKey:@"name"]; 
       // Set location name to your textView 
       textView.text = locationName; 
      } 
    }); 
} 

這裏kGoogleSDKBrowserKey是您註冊的API密鑰。另請參閱how to register for Google Places

0

你將不得不實施UITextFieldDelegate, 在textField:shouldChangeCharactersInRange:replacementString方法,你應該有這樣的事情:

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{ 
    NSString *substring = [NSString stringWithString:textField.text]; 
    substring = [substring stringByReplacingCharactersInRange:range withString:string]; 
    substring = [substring stringByReplacingOccurrencesOfString:@" " withString:@""]; 

    // your code to send the search string to google place API 
    return YES; 
} 

當你的搜索請求,谷歌的地方API完成後不要忘記重新加載您的UITableView的數據使用:[yourTable reloadData]

希望這會有所幫助。

乾杯。