当前位置:   article > 正文

iOS 百度地图的模糊搜索地址以及回调的使用

ios百度地图sdk sug检索发送成功没有回调

iOS 百度地图的模糊搜索地址以及回调的使用

    前一段时间一直在写一个打车的 app, 所以用到了百度地图,在这里先吐槽一下,百度地图的官方文档真的不怎么详细,好在有 demo, 地图 sdk 文档写的最详细的应该就是高德的了,个人觉得,其他的没有比较,腾讯地图没看,因为公司要求用百度地图,无奈之举了,好啦,言归正传,下面就详细的介绍一下百度地图定位与模糊搜索的一般使用吧!!!

    1.用百度地图当然需要当官方网站里面注册 app, 申请 appKey 和 secret, 注意绑定的 bundle id 一定要和自己项目的 bundle id 一致,否则 mapview 无法加载.

    2.导入 sdk, 两种方法,直接导入和 cocoapods,这些都是官方文档里面已经写得很详细了.

    3.直接进入主要的内容吧,时间有限.

    a.appdelegate 中的

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {   

    // 要使用百度地图,请先启动BaiduMapManager

    _mapManager = [[BMKMapManager alloc]init];

    // 如果要关注网络及授权验证事件,请设定     generalDelegate参数

    BOOL ret = [_mapManager start:@"百度地图秘钥"  generalDelegate:nil];

    if (!ret) {

        NSLog(@"manager start failed!");

    }

  return YES;

}

b.然后就是 viewController 

(1)导入百度地图相关的.h 文件,(设置代理事件)

@interface HomeViewController ()<BMKMapViewDelegate,BMKGeoCodeSearchDelegate,BMKLocationServiceDelegate>

{

    BMKPinAnnotationView *newAnnotation;

    BMKGeoCodeSearch *_geoCodeSearch;

    BMKReverseGeoCodeOption *_reverseGeoCodeOption;

    BMKLocationService *_locService;

    BMKRouteSearch *routeSearch;//路径规划

}

@property (nonatomic,strong) BMKMapView *mapView;

@property (weak, nonatomic) UIButton *mapPin;

 

-(NSMutableArray *)cityDataArr

{

    if (_cityDataArr==nil)

    {

        _cityDataArr=[NSMutableArray arrayWithCapacity:0];

    }

      return _cityDataArr;

}

#pragma mark 初始化地图,定位

-(void)initLocationService

{   

    //设置了 navigationBar 的 translucent 属性,屏幕整体下移64个像素

    _mapView = [[BMKMapView alloc] initWithFrame:CGRectMake(0, -64, kScreen_width, kScreen_height)];

    [_mapView setMapType:BMKMapTypeStandard];// 地图类型 ->卫星/标准、

     _mapView.zoomLevel = 25;//缩放比例,越大,定位越精确,但是地图显示的范围有限

    [_mapView setBuildingsEnabled:YES];

    _mapView.delegate = self;//代理事件,用完一定要置空,要不然就内存泄露

    _mapView.showsUserLocation = YES;//显示定位点

    [_mapView bringSubviewToFront:_mapPin];

    

    if (_locService==nil) {

        _locService = [[BMKLocationService alloc]init];

        [_locService setDesiredAccuracy:kCLLocationAccuracyBest];

    }

    

    _locService.delegate = self;

    [_locService startUserLocationService];

    

    _mapView.showsUserLocation = NO;//先关闭显示的定位图层

    _mapView.userTrackingMode = BMKUserTrackingModeFollow;//设置定位的状态

    _mapView.showsUserLocation = YES;//显示定位图层

    [self.view addSubview:self.mapView];

    [self.mapView addSubview:self.centerImgView];

    //定位展示视图

    BMKLocationViewDisplayParam *displayParam = [[BMKLocationViewDisplayParam alloc]init];

    displayParam.isAccuracyCircleShow = false;//精度圈是否显示

    [_mapView updateLocationViewWithParam:displayParam];

    //添加视图到 mapView 上面

    [self creatViewOnmapView];

}

 

#pragma mark BMKLocationServiceDelegate

- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation

{

    _mapView.showsUserLocation = YES;//显示定位图层

       //设置地图中心为用户经纬度

    [_mapView updateLocationData:userLocation];

    //_mapView.centerCoordinate = userLocation.location.coordinate;

    //   BMKCoordinateRegion region ;//表示范围的结构体

    //    region.center = _mapView.centerCoordinate;//中心点

    //    region.span.latitudeDelta = 0.004;//经度范围(设置为0.1表示显示范围为0.2的纬度范围)

    //    region.span.longitudeDelta = 0.004;//纬度范围

    //     [_mapView setRegion:region animated:YES];

}

 

#pragma mark ------- 视图将要消失,做一些操作

-(void)viewWillDisappear:(BOOL)animated

{

    [_mapView viewWillDisappear];

    _mapView.delegate = nil;

    _locService.delegate = nil;

    _geoCodeSearch.delegate = nil;

    routeSearch.delegate = nil;

}

 

-(void)dealloc

{

    if (_mapView) {

        _mapView = nil;

    }

}

这样一个简单的定位的功能的百度地图就已经好了.

 

4.下面就是模糊搜索了

同样导入相关的头文件,设置相关代理,实现相关代理事件

typedef void(^FinishBlock)(NSString *address,CLLocationCoordinate2D pt);//传回地址和百度地图经纬度

@interface SearchViewController : UIViewController

@property (nonatomic,strong) UITextField *inputAddTF;//输入地址框

@property (weak, nonatomic) IBOutlet UITableView *displayTableView;//显示的tableView

@property (nonatomic,strong) NSString *placeStr;

@property (nonatomic,strong) FinishBlock block;//回调的 block

@property (nonatomic,strong) NSString *locationCity;//定位城市

@end

@interface SearchViewController ()<BMKPoiSearchDelegate,BMKGeoCodeSearchDelegate,UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>

{

    BMKPoiSearch *_poisearch;            //poi搜索

    BMKGeoCodeSearch  *_geocodesearch;   //geo搜索服务

}

@property (nonatomic,strong) NSMutableArray *addressArray;//搜索的地址数组

@property (nonatomic,strong) SearchModel *model;

 

- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];

//自动让输入框成为第一响应者,弹出键盘

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

        [self.inputAddTF becomeFirstResponder];

    });

}

 

-(void)viewWillDisappear:(BOOL)animated

{

    [super viewWillDisappear:animated];

    _poisearch.delegate = nil; // 不用时,置nil

    _geocodesearch.delegate = nil;

}

- (void)viewDidLoad {

    [super viewDidLoad];

    _inputAddTF = [[UITextField alloc] initWithFrame:CGRectMake(0, 10, 200*RATIO, 30*RATIO)];

    self.inputAddTF.attributedPlaceholder = [self setPlaceHolderString:self.placeStr];

    [self.inputAddTF addTarget:self action:@selector(inputAddTFAction:) forControlEvents:UIControlEventEditingChanged];

    self.inputAddTF.borderStyle =UITextBorderStyleNone;

    self.inputAddTF.backgroundColor = COLOR_BTN;

    self.inputAddTF.textAlignment = NSTextAlignmentCenter;

    self.displayTableView.dataSource = self;

    self.displayTableView.delegate = self;

    self.inputAddTF.font = [UIFont boldSystemFontOfSize:18*RATIO];

    self.inputAddTF.textColor = [UIColor colorWithWhite:20 alpha:7];

    self.navigationItem.titleView = _inputAddTF;

}

#pragma mark TableViewDelegate

//设置 row

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    return self.addressArray.count;

}

//设置 tableViewCell

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{

    static NSString *cell_id = @"cell_id";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cell_id];

    if (!cell) {

        cell = [[UITableViewCell alloc] initWithStyle:3 reuseIdentifier:cell_id];

    }

    SearchModel *sModel = [[SearchModel alloc] init];

    sModel = self.addressArray[indexPath.row];

    cell.textLabel.text = sModel.name;

    cell.textLabel.font = [UIFont systemFontOfSize:15];

    NSString *str = @"676767";

    cell.textLabel.textColor =  UIColorFromRGBString(str);

    cell.detailTextLabel.text = sModel.address;

    cell.detailTextLabel.textColor = [UIColor colorWithRed:157/255.0 green:157/255.0 blue:157/255.0 alpha:1];

    return cell;

}

//设置选中事件

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

{

    SearchModel *model = [[SearchModel alloc] init];

    model = self.addressArray[indexPath.row];

    [self.navigationController popViewControllerAnimated:YES];

      //block 传值

    __weak typeof(self) wSelf = self;

    wSelf.block(model.address,model.pt);   

}

#pragma mark ---- 设置高度 

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{

    return 50;

}

 

#pragma mark 监听输入文本信息

-(void)inputAddTFAction:(UITextField *)textField

{

    //延时搜索

    [self performSelector:@selector(delay) withObject:self afterDelay:0.5];

}

 

#pragma mark ----- 延时搜索

- (void)delay {

    [self nameSearch];

}

 

#pragma mark ---- 输入地点搜索

-(void)nameSearch

{

        _poisearch = [[BMKPoiSearch alloc]init];

        _poisearch.delegate = self;

        BMKCitySearchOption *citySearchOption = [[BMKCitySearchOption alloc]init];

        citySearchOption.pageIndex = 0;

        citySearchOption.pageCapacity = 30;

        citySearchOption.city= _locationCity;

        citySearchOption.keyword = self.inputAddTF.text;

        BOOL flag = [_poisearch poiSearchInCity:citySearchOption];

        if(flag)

        {

            NSLog(@"城市内检索发送成功");

        }

        else

        {

            NSLog(@"城市内检索发送失败");

        }

}

#pragma mark --------- poi 代理方法

-(void)onGetPoiResult:(BMKPoiSearch *)searcher result:(BMKPoiResult *)poiResult errorCode:(BMKSearchErrorCode)errorCode

{

    if(errorCode == BMK_SEARCH_NO_ERROR)

    {

        self.addressArray = [NSMutableArray array];

        [self.addressArray removeAllObjects];

        for (BMKPoiInfo *info in poiResult.poiInfoList) {

            _model = [[SearchModel alloc] init];

            _model.name = info.name;

            _model.address = info.address;

            _model.pt = info.pt;

             [self.addressArray addObject:_model];

        }

        [self.displayTableView reloadData];

    }

}

 

#pragma mark 滑动的时候收起键盘

- (void)scrollViewDidScroll:(UIScrollView *)scrollView

{

    [self.view endEditing:YES];

    [self.navigationItem.titleView endEditing:YES];

}

 

-(void)dealloc

{

    if (_poisearch != nil) {

        _poisearch = nil;

    }

    if (_geocodesearch != nil) {

        _geocodesearch = nil;

    }

}

//这样一个简单的搜索功能就实现了,时间问题,就没那么多时间写了,有疑问可以留言

 

 

转载于:https://my.oschina.net/alanTang123/blog/704942

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/290432
推荐阅读
相关标签
  

闽ICP备14008679号