2015-10-17 28 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]

希望这会有所帮助。

干杯。