IOS使用百度地图-定位功能

第一步:设置mapManager 获取gps使用授权

注意:自iOS8起,系统定位功能进行了升级,SDK为了实现最新的适配,自v2.5.0起也做了相应的修改,开发者在使用定位功能之前,需要在info.plist里添加(以下二选一,两个都添加默认使用NSLocationWhenInUseUsageDescription):
NSLocationWhenInUseUsageDescription ,允许在前台使用时获取GPS的描述
NSLocationAlwaysUsageDescription ,允许永久使用GPS的描述

在AppDelegate.m文件中
    @property (nonatomic,strong)BMKMapManager * mapManager;
    
    在didFinishLaunchingWithOptions方法里面添加下面的代码
    //1.初始化mapManager
    _mapManager = [[BMKMapManager alloc]init];
    //如果要关注网络及授权验证事件,请设定generalDelegate参数
    BOOL ret = [_mapManager start:@"jbAxq484vaLKdNn4GjAD0NYY"  generalDelegate:nil];
    if (!ret) {
        NSLog(@"manager start failed!");
    }
    //2.获取授权
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //由于IOS8中定位的授权机制改变 需要进行手动授权
        CLLocationManager  *locationManager = [[CLLocationManager alloc] init];
        //获取授权认证
        [locationManager requestAlwaysAuthorization];
        [locationManager requestWhenInUseAuthorization];
    }
-----------------------------------------------------
//特别注意:
由于iOS9改用更安全的https,为了能够在iOS9中正常使用地图SDK,请在"Info.plist"中进行如下配置,否则影响SDK的使用。
    <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
    </dict>


第二步:设置初始化控件

/*
 * 初始化百度地图 定位时需要的数据
 */
- (void)initBaiduMap
{
    //1.初始化mapView
    BMKMapView* mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 0, 375, 665)];
    self.mapView = mapView;
    [self.view addSubview:self.mapView];
    //设置代理
    self.mapView.delegate = self;
    //设置标准模式
    self.mapView.mapType = BMKMapTypeStandard;
    self.mapView.showsUserLocation = NO;//先关闭显示的定位图层
    
    
    //2.初始化BMKLocalService
    self.locService = [[BMKLocationService alloc]init];
    self.locService.delegate = self;

}


第三步:设置开启定位/关闭定位按钮

//点击开始定位按钮
- (IBAction)startLocation:(id)sender {
    //开启gps定位
    [self.locService startUserLocationService];
    self.mapView.showsUserLocation = YES;
    self.mapView.userTrackingMode = BMKUserTrackingModeNone;
    
}


//点击取消定位按钮
- (IBAction)stopLocation:(id)sender {
    //关闭gps定位
    self.mapView.showsUserLocation = NO;
    [self.locService stopUserLocationService];
    
}


第四步:设置BMKMapViewDelegate 

#pragma mark BMKLocalService代理
/**
 *用户方向更新后,会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    NSLog(@"heading is %@",userLocation.heading);
     [_mapView updateLocationData:userLocation];
}
//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{

    //    NSLog(@"当前的坐标是: %f,%f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);

    //这句话的作用就是把地图的中心设置成定位后的坐标
    self.mapView.centerCoordinate = userLocation.location.coordinate;
    [_mapView updateLocationData:userLocation];
}

第五步:程序启动后,点击开始定位按钮

你可能感兴趣的:(IOS使用百度地图-定位功能)