美文网首页
iOS使用百度地图-显示当前定位、逆地理编码、导航

iOS使用百度地图-显示当前定位、逆地理编码、导航

作者: 小鲜肉老腊肉都是肉 | 来源:发表于2019-10-14 10:35 被阅读0次

1. 显示地图

    1.1  pch导入头文件
    #import <BaiduMapAPI_Base/BMKBaseComponent.h>
    #import <BaiduMapAPI_Map/BMKMapComponent.h>
    #import <BaiduMapAPI_Search/BMKSearchComponent.h>
    #import <BaiduMapAPI_Cloud/BMKCloudSearchComponent.h>
    #import <BaiduMapAPI_Utils/BMKUtilsComponent.h>
    #import <BaiduMapAPI_Map/BMKMapView.h>
    #import <BMKLocationkit/BMKLocationAuth.h>
    #import <BMKLocationKit/BMKLocationManager.h>
    
    1.2  AppDelegate.m文件设置AK
    BMKMapManager *mapManager = [[BMKMapManager alloc] init];
    //设置地图AK
    BOOL ret = [mapManager start:@"XXXXXX"  generalDelegate:nil];
    //设置定位AK     
    [[BMKLocationAuth sharedInstance] checkPermisionWithKey:@"XXXXXX" authDelegate:self];

    1.3   设置代理
    @interface ViewController ()<BMKMapViewDelegate/*地图代理*/,
                                 BMKLocationManagerDelegate/*定位代理*/,
                                 BMKGeoCodeSearchDelegate/*你地理编码代理*/>

    1.4   地图声明为属性
    @property (nonatomic, strong) BMKMapView *mapView;
    
    1.5   懒加载初始化地图
    -(BMKMapView *)mapView
    {
        if (!_mapView)
        {
            _mapView = [[BMKMapView alloc] initWithFrame:CGRectMake(0, NaviHigh, ScreenWidth, ScreenHeight - NaviHigh)];
            _mapView.delegate = self;
            _mapView.showMapScaleBar = YES;
            _mapView.showsUserLocation = YES;
            _mapView.zoomLevel = 14;
        }
        return _mapView;
    }

     1.6   把地图添加到页面上
     [self.view addSubview:self.mapView];

     1.7   地图其他设置
    -(void)viewWillAppear:(BOOL)animated
    {
            [super viewWillAppear:animated];
            [_mapView viewWillAppear];
    }
    -(void)viewWillDisappear:(BOOL)animated
    {
            [super viewWillDisappear:animated];
            [_mapView viewWillDisappear];
    }

2. 地图定位到当前位置

    2.1   导入头文件  --步骤1.1已经导入了
    #import <BMKLocationKit/BMKLocationManager.h>

    2.2   设置代理  --步骤1.3已经设置了
    @interface ViewController ()<BMKLocationManagerDelegate>

    2.3   声明定位服务相关属性
    @property (nonatomic, strong) BMKLocationManager *locationManager;

    2.4   懒加初始化载定位服务相关属性
    -(BMKLocationManager *)locationManager
    {
        if (!_locationManager)
        {
            _locationManager = [[BMKLocationManager alloc] init];
            _locationManager.delegate = self;
            _locationManager.coordinateType = BMKLocationCoordinateTypeBMK09LL;
            _locationManager.distanceFilter = kCLLocationAccuracyBestForNavigation;
            _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
            _locationManager.activityType = CLActivityTypeAutomotiveNavigation;
            _locationManager.pausesLocationUpdatesAutomatically = NO;
            // YES的话是可以进行后台定位的,但需要项目配置,否则会报错,具体参考开发文档
            _locationManager.allowsBackgroundLocationUpdates = NO;
            _locationManager.locationTimeout = 10;
            _locationManager.reGeocodeTimeout = 10;
        }
       return _locationManager;
    }

    2.5  开启定位,放在1.6添加地图后面
    [self.locationManager startUpdatingLocation];

    2.6  实现代理方法
    #pragma mark - 定位至当前位置 -
    - (void)BMKLocationManager:(BMKLocationManager * _Nonnull)manager didUpdateLocation:(BMKLocation * _Nullable)locatio orError:(NSError * _Nullable)error
    {
        if (locatio)
        {
            //显示当前位置
            BMKUserLocation * loca = [[BMKUserLocation alloc] init];
            loca.location = locatio.location;
            [self.mapView updateLocationData:loca];
            [self.mapView setCenterCoordinate:locatio.location.coordinate animated:YES];
        }
    }

3.点击地图显示大头针

    3.1   声明全局属性的大头针
    @property(nonatomic , strong) BMKPointAnnotation *annotation; 

    3.2   点击地图显示大头针
    #pragma mark - 地图点击事件 -
    -(void)mapView:(BMKMapView *)mapView  onClickedMapBlank:(CLLocationCoordinate2D)coordinate
    {
            if (self.annotation)
            {
                [self.mapView removeAnnotation:self.annotation];
            }
            self.annotation = [[BMKPointAnnotation alloc]init];
            self.annotation.coordinate = coordinate;
            self.annotation.title = @"消防栓位置";
            [self.mapView addAnnotation:self.annotation];
            [self.mapView setCenterCoordinate:coordinate animated:YES];
    }

4.逆地理编码

    4.1   声明全局属性的逆地理编码检索对象
    @property(nonatomic , strong) BMKGeoCodeSearch *search;

    4.2   初始化逆地理编码检索对象
    -(BMKGeoCodeSearch *)search
    {
        if (!_search)
        {
            _search = [[BMKGeoCodeSearch alloc] init];
            _search.delegate = self;
        }
        return _search;
    }

    4.3   在地图点击事件onClickedMapBlank中进行逆地理编码检索
    //构造逆地理编码检索参数
    BMKReverseGeoCodeSearchOption *reverseGeoCodeOption = [[BMKReverseGeoCodeSearchOption alloc]init];
    reverseGeoCodeOption.location = coordinate;
    // 是否访问最新版行政区划数据(仅对中国数据生效)
    reverseGeoCodeOption.isLatestAdmin = YES;
    //发起逆地理编码检索请求
    BOOL flag = [self.search reverseGeoCode: reverseGeoCodeOption];
    if (flag)
    {
            NSLog(@"逆geo检索发送成功");  
    }  
    else 
    {
            NSLog(@"逆geo检索发送失败");  
    }

    4.4   逆地理编码代理方法
    - (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeSearchResult *)result errorCode:(BMKSearchErrorCode)error
    {
       if (error == BMK_SEARCH_NO_ERROR)
       {
       //在此处理正常结果
        BMKPoiInfo *POIInfo = result.poiList[0];
        BMKSearchRGCRegionInfo *regionInfo = [[BMKSearchRGCRegionInfo alloc] init];
        if (result.poiRegions.count > 0)
        {
        regionInfo = result.poiRegions[0];
        }
        NSString *message = [NSString stringWithFormat:@"经度:%f\n纬度:%f\n地址名称:%@\n商圈名称:%@\n可信度:%ld\n国家名称:%@\n省份名称:%@\n城市名称:%@\n区县名称:%@\n乡镇:%@\n街道名称:%@\n街道号码:%@\n行政区域编码:%@\n国家代码:%@\n方向:%@\n距离:%@\nPOI名称:%@\nPOI经纬坐标:%f\nPOI纬度坐标:%f\nPOI地址信息:%@\nPOI电话号码:%@\nPOI的唯一标识符:%@\nPOI所在省份:%@\nPOI所在城市:%@\nPOI所在行政区域:%@\n街景ID:%@\n是否有详情信息:%d\nPOI方向:%@\nPOI距离:%ld\nPOI邮编:%ld\n相对位置关系:%@\n归属区域面名称:%@\n归属区域面类型:%@\n语义化结果描述:%@",
                         result.location.longitude,
                         result.location.latitude,
                         result.address,
                         result.businessCircle,
                         (long)result.confidence,
                         result.addressDetail.country,
                         result.addressDetail.province,
                         result.addressDetail.city,
                         result.addressDetail.district,
                         result.addressDetail.town,
                         result.addressDetail.streetName,
                         result.addressDetail.streetNumber,
                         result.addressDetail.adCode,
                         result.addressDetail.countryCode,
                         result.addressDetail.direction,
                         result.addressDetail.distance,
                         POIInfo.name,
                         POIInfo.pt.longitude,
                         POIInfo.pt.latitude,
                         POIInfo.address,
                         POIInfo.phone,
                         POIInfo.UID,
                         POIInfo.province,
                         POIInfo.city,
                         POIInfo.area,
                         POIInfo.streetID, POIInfo.hasDetailInfo, POIInfo.direction, (long)POIInfo.distance, (long)POIInfo.zipCode, regionInfo.regionDescription, regionInfo.regionName, regionInfo.regionTag, result.sematicDescription];
    
        NSLog(@"--->%@",message);
       }
       else {
           NSLog(@"检索失败");
       }
    }

5.导航

    我用的导航SDK为旧版本SDK,使用新版本SDK会报很多错误,因此一直没更新

    5.1  导入SDK
导航sdk
    5.2  Link Binary With Libraries导入系统库
    Accelerate.framework
    CallKit.framework
    AdSupport.framework
    AssetsLibrary.framework
    libiconv.tbd
    UserNotifications.framework
    MediaPlayer.framework
    libc++.tbd
    CoreLocation.framework
    libsqlite3.0.tbd

    5.3  配置plist文件
    <key>NSLocationAlwaysUsageDescription</key>
    <string>只有开启定位功能才能正常使用百度导航</string>                                 
    <key>NSLocationWhenInUseUsageDescription</key> 
    <string>只有开启定位功能才能正常使用百度导航</string> 
    <key>UIBackgroundModes</key>         
            <array> 
                    <string>audio</string> 
                    <string>location</string>
             </array> 
     <key>UIViewControllerBasedStatusBarAppearance</key>
     <false/>
     <key>LSApplicationQueriesSchemes</key>
             <array> 
                    <string>baidumap</string>
             </array>

    5.3  
    旧版本导航SDK
    AppDelegate.m导航AK设置和TTS语音设置
    [BNCoreServices_Instance startServicesAsyn:^{
            [BNCoreServices_Instance authorizeNaviAppKey:@"XXXX" completion:^(BOOL suc)
    {
    }];
    
    //TTS SDK鉴权
    [BNCoreServices_Instance authorizeTTSAppId:@"XXXX"
                                        apiKey:@"XXXX"
                                     secretKey:@"XXXX"
                                    completion:^(BOOL suc) {
                                        NSLog(@"authorizeTTS ret = %d",suc);
                                    }];
      } fail:^{
      }];
   
    5.3  导入导航头文件
    #import "BNCoreServices.h"

    5.3  设置代理
    @interface mainVC ()<BNNaviRoutePlanDelegate,BNNaviUIManagerDelegate>

    5.3  开始导航
    //节点数组
    NSMutableArray *nodesArray = [[NSMutableArray alloc]    initWithCapacity:2];

    //起点         当前位置
    BNRoutePlanNode *startNode = [[BNRoutePlanNode alloc] init];
    startNode.pos = [[BNPosition alloc] init];
    startNode.pos.x = self.currentLocation.longitude;
    startNode.pos.y = self.currentLocation.latitude;
    startNode.pos.eType = BNCoordinate_BaiduMapSDK;
    [nodesArray addObject:startNode];

    //终点
    BNRoutePlanNode *endNode = [[BNRoutePlanNode alloc] init];
    endNode.pos = [[BNPosition alloc] init];
    endNode.pos.x = [dict[@"devicesLongitude"] floatValue];
    endNode.pos.y = [dict[@"devicesLatitude"] floatValue];
    endNode.pos.eType = BNCoordinate_BaiduMapSDK;
    [nodesArray addObject:endNode];

    // 发起算路
    [BNCoreServices_RoutePlan  startNaviRoutePlan: BNRoutePlanMode_Recommend naviNodes:nodesArray time:nil delegete:self userInfo:nil];

    5.3  设置代理方法
    //算路成功回调
    -(void)routePlanDidFinished:(NSDictionary *)userInfo
    {
        NSLog(@"算路成功");

        //路径规划成功,开始导航
        [BNCoreServices_UI showPage:BNaviUI_NormalNavi delegate:self extParams:nil];
    }

    //算路失败回调
    - (void)routePlanDidFailedWithError:(NSError *)error andUserInfo:(NSDictionary *)userInfo
    {
        NSLog(@"算路失败");
        switch ([error code]%10000)
        {
            case BNAVI_ROUTEPLAN_ERROR_LOCATIONFAILED:
                NSLog(@"暂时无法获取您的位置,请稍后重试");
                break;
            case BNAVI_ROUTEPLAN_ERROR_ROUTEPLANFAILED:
                NSLog(@"无法发起导航");
                break;
            case BNAVI_ROUTEPLAN_ERROR_LOCATIONSERVICECLOSED:
                NSLog(@"定位服务未开启,请到系统设置中打开定位服务。");
                break;
            case BNAVI_ROUTEPLAN_ERROR_NODESTOONEAR:
                NSLog(@"起终点距离起终点太近");
                break;
            default:
                NSLog(@"算路失败");
                break;
        } 
    }

    //算路取消
    -(void)routePlanDidUserCanceled:(NSDictionary*)userInfo 
    {
        NSLog(@"算路取消");
    }
    //退出导航页面回调
    - (void)onExitPage:(BNaviUIType)pageType  extraInfo:(NSDictionary*)extraInfo
    {
        if (pageType == BNaviUI_NormalNavi)
        {
           NSLog(@"退出导航");
        }
        else if (pageType == BNaviUI_Declaration)
        {
            NSLog(@"退出导航声明页面");
        }
    }

相关文章

网友评论

      本文标题:iOS使用百度地图-显示当前定位、逆地理编码、导航

      本文链接:https://www.haomeiwen.com/subject/zwglmctx.html