如何使用gmsAutocomplete视图控制器在uitextfield上应用自定义搜索以进行地点搜索。

时间:2016-05-03 09:55:49

标签: ios google-maps autocomplete

  

我正在使用我的应用程序中的GMSAutocompleteViewController。我在视图控制器中有一个uitextfield当我使用谷歌api搜索文本字段搜索一个地方时,一个新视图打开,由谷歌提供支持。请看我的代码。

- (void)textFieldDidBeginEditing:(UITextField *)textField
 {



tappedTextField = textField;
        GMSAutocompleteViewController *acController = [[GMSAutocompleteViewController alloc] init];
        acController.delegate = self;
        [self presentViewController:acController animated:YES completion:nil];



  }


  - (void)viewController:(GMSAutocompleteViewController *)viewController
   didAutocompleteWithPlace:(GMSPlace *)place {
// Do something with the selected place.
NSLog(@"Place name %@", place.name);
NSLog(@"Place address %@", place.formattedAddress);
NSLog(@"Place attributions %@", place.attributions.string);
NSLog(@"lat and log%f", place.coordinate.latitude);
NSLog(@"lang %f", place.coordinate.longitude);



   tappedTextField.text = place.name;



[self dismissViewControllerAnimated:YES completion:nil];
}

  - (void)viewController:(GMSAutocompleteViewController *)viewController
    didFailAutocompleteWithError:(NSError *)error {
// TODO: handle the error.
      NSLog(@"error: %ld", (long)[error code]);
     [self dismissViewControllerAnimated:YES completion:nil];
     }

  // User canceled the operation.
- (void)wasCancelled:(GMSAutocompleteViewController *)viewController {
NSLog(@"Autocomplete was cancelled.");
[self dismissViewControllerAnimated:YES completion:nil];
   }
  

我不想移动到textfield tapp上的另一个视图进行搜索。我可以只从文本字段中搜索地点吗?

Scrren of my view controller

  

当我点击目标文本字段时,会出现一个用于搜索的新视图,但我需要在文本字段中搜索,只需在tapp文本字段后在屏幕上搜索。

This screen after click of textfield

3 个答案:

答案 0 :(得分:4)

听起来就像你在文本字段处于活动状态时(即this类似的东西)在文本字段下面的表格中显示自动完成结果。

您可以通过创建在UI中正确位置显示的UITableView来实现此目的。不要使用GMSAutocompleteViewController,而是创建GMSAutocompleteTableDataSource并将其设置为UITableView的委托和数据源。例如:

_tableDataSource = [[GMSAutocompleteTableDataSource alloc] init];
_tableDataSource.delegate = self;
tableView.delegate = _tableDataSource;
tableView.dataSource = _tableDataSource;

当文本字段文本发生更改时,请在表数据源上调用sourceTextHasChanged

[_tableDataSource sourceTextHasChanged:textField.text];

最后,让父视图控制器实现GMSAutocompleteTableDataSourceDelegate协议

GoogleMaps CocoaPod中包含的示例应用程序中有一些示例代码,它们与您的需求非常接近。在下载的Pods目录中查找SDKDemoAutocompleteWithTextFieldController.m

答案 1 :(得分:1)

我使用此代码来实现您所要求的相同行为。

-(void)LoadJson_search{
searchArray=[[NSMutableArray alloc]init];
NSLog(@"str......%@",strSearch);

NSString *str1 = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/autocomplete/json?input=%@&key=AIzaSyD2NttUhPQ4PKvpju97qpeWj8SYnZtzt0s",strSearch];
NSLog(@"%@",strSearch);
NSURL *url = [NSURL URLWithString:str1];

NSData *data = [NSData dataWithContentsOfURL:url];
NSError *error=nil;
if(data.length==0)
{

}
else
{
    NSDictionary *jsondic= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

    // NSLog(@"1,,,,%@",jsondic);
    [searchArray removeAllObjects];
    if([[jsondic objectForKey:@"status"]isEqualToString:@"ZERO_RESULTS"])
    {

    }
    else if([[jsondic objectForKey:@"status"]isEqualToString:@"INVALID_REQUEST"])
    {
    }
    else
    {
        for(int i=0;i<[jsondic.allKeys count];i++)
        {
            //['predictions'][0]['description']
            NSString *str1=[[[jsondic objectForKey:@"predictions"] objectAtIndex:i] objectForKey:@"description"];
            [searchArray  addObject:str1];
        }
        tbl_vw1.hidden=FALSE;
    }
    if (searchArray.count == 0) {
        tbl_vw1.hidden = TRUE;
    }
    else{
        [tbl_vw1 reloadData];
    }
}
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;{
if (textField.tag == 3) {
    strSearch = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if([string isEqualToString:@" "]){

    }
    else{
        [self LoadJson_search];
    }
}
return YES;
}

在tableview上选择方法使用以下

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
strSelectedAddress = [searchArray objectAtIndex:indexPath.row];
[self.eventDict setObject:strSelectedAddress forKey:@"venue"];
//[self geoCodeUsingAddress:str_select_address];

tbl_vw1.hidden=TRUE;
[tbl_vw reloadData];
}

重新加载表后,在cellForRowAtIndexpath中使用它来更新选定的地名。

cell.txt.text = [self.eventDict objectForKey:@"venue"];

希望这会对你有所帮助。 :)

答案 2 :(得分:0)

这是基于@Nij的答案。这将使您完全满意......

#import "ViewController.h"
#import <GooglePlaces/GooglePlaces.h>

@interface ViewController () <UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource> {

    NSMutableArray *searchArray;
    NSString *strSearch;

}

@property (weak, nonatomic) IBOutlet UITextField *searchTextfeild;
@property (weak, nonatomic) IBOutlet UITableView *tbl_vw1;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    _searchTextfeild.delegate = self;
    _tbl_vw1.delegate = self;
    _tbl_vw1.dataSource = self;
    _tbl_vw1.hidden = YES;

    _searchTextfeild.clearButtonMode = UITextFieldViewModeAlways;

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)LoadJson_search{

    searchArray=[[NSMutableArray alloc]init];
    //    NSLog(@"str......%@",strSearch);
    // This API key is from https://developers.google.com/maps/web/
    NSString *str1 = [NSString stringWithFormat:@"https://maps.googleapis.com/maps/api/place/queryautocomplete/json?input=%@&key=AIzaSyAm7buitimhMgE1dKV2j4_7doULluiiDzU", strSearch];
    NSURL *url = [NSURL URLWithString:str1];

    NSData *data = [NSData dataWithContentsOfURL:url];
    NSError *error=nil;
    if(data.length==0)
    {

    }
    else
    {
        NSDictionary *jsondic= [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

    //         NSLog(@"1,,,,%@",jsondic);
        [searchArray removeAllObjects];
        if([[jsondic objectForKey:@"status"]isEqualToString:@"ZERO_RESULTS"])
        {

        }
        else if([[jsondic objectForKey:@"status"]isEqualToString:@"INVALID_REQUEST"])
        {
        }
        else
        {
            for(int i=0;i<[jsondic.allKeys count];i++)
            {
                NSString *str1=[[[jsondic objectForKey:@"predictions"] objectAtIndex:i] objectForKey:@"description"];
                [searchArray  addObject:str1];
            }
            _tbl_vw1.hidden = NO;
    //            NSLog(@"%@", searchArray);
        }
        if (searchArray.count == 0) {
            _tbl_vw1.hidden = YES;
        }else{
            [_tbl_vw1 reloadData];
        }
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;{
    if (textField.tag == 3) {
        strSearch = [textField.text stringByReplacingCharactersInRange:range withString:string];
         if([string isEqualToString:@" "]){

         }else{
             [self LoadJson_search];
         }
    }
    return YES;
}


- (BOOL)textFieldShouldClear:(UITextField *)textField{
    _tbl_vw1.hidden = YES;
     [_tbl_vw1 reloadData];

    return YES;
}


//TableView delegates
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return searchArray.count;
}


 -(UITableViewCell *)tableView:(UITableView*)aTableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {

    UITableViewCell *cell = [_tbl_vw1 dequeueReusableCellWithIdentifier:@"cell"];
    if(!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    }
//    NSLog(@"searchArray ==== %@", searchArray);
    cell.textLabel.text = [searchArray objectAtIndex:indexPath.row];

    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    _searchTextfeild.text = [searchArray objectAtIndex:indexPath.row];

    _tbl_vw1.hidden = YES;
    [_tbl_vw1 reloadData];

}