ios LBS定位开发初探(V2.6)

一、引入baiduSDK

1、下载http://api.map.baidu.com/lbsapi/cloud/sdk-ios.htm

2、申请21位密钥,这里面要填个安全码,所谓的安全码就是工程的 Build Identifier (注意:这里一定要填写完整)

3 、导入完成编译会出现一连串错误,记住工程里面随便找个.m文件,把其后缀修改成.mm就没事

4、有一个非常重要的地方就是在plist文件添加两个字段:NSLocationWhenInUseUsageDescription 和 NSLocationAlwaysUsageDescription 属性都为string ,值为空

二、申请密钥

1、填写安全码,即build identifier

2、安全码的重要性:没有安全码定位根本不会成功

三、静态库文件 (.a文件 这里面有两个,一个是在真机上运行的,一个是在模拟器上面运行的,可直接上真机上运行,或者合成两个.a文件)

1、一般来说,可以直接上真机的.a静态文件

2、麻烦一点就是将真机和模拟机的静态文件合成,打开电脑终端,执行命令行 合成.a文件 (该文件在真机和模拟器上都可以运行)

 lipo –create Release-iphoneos/libbaidumapapi.a Release-iphonesimulator/libbaidumapapi.a –output libbaidumapapi.a

注意:将两个静态库.a文件同时放置在桌面,然后打开终端执行命令行,生成的.a文件也是在桌面,拉进工程即可使用。

四、剩下的就是代码

1、导入BMapKit.h,遵循代理 BMKGeneralDelegate 、BMKLocationServerceDelegate 、BMKGeoCodeSearchDelegate

2、定义三变量 .h文件里面(你定位的类里面,不一定要.mm文件)
//定位服务
BMKLocationService *_locationService;
//反编码
BMKGeoCodeSearch *_geocodesearch;
//地图
BMKMapManager* _mapManager;
//定位服务
@property (nonatomic,strong) BMKLocationService *locationService;
//反编码
@property (nonatomic,strong) BMKGeoCodeSearch *geocodesearch;

3、使用前面申请的秘钥(简称为授权,一定要在定位之前授权)
//授权
BOOL ret = [_mapManager start:@“这里添加你申请的密钥“ generalDelegate:self];

if (!ret) {

    NSLog(@"manager start failed!");

}

4、开始定位
//定位处理
_locationService = [[BMKLocationService alloc]init];

_geocodesearch = [[BMKGeoCodeSearch alloc]init];


_locationService.delegate = self;
 //反编码代理
_geocodesearch.delegate = self;


//开始定位
[_locationService startUserLocationService];

5、获取当前位置的经纬度还有具体地址

pragma mark - 百度地图定位的代理方法

  • (void)didUpdateUserLocation:(BMKUserLocation *)userLocation
    {

    NSLog(@”didUpdateUserLocation lat %f,long %f”,userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);

    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude};

    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];

    reverseGeocodeSearchOption.reverseGeoPoint = pt;
    BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];
    if(flag)
    {
    NSLog(@”反geo检索发送成功”);

    }
    else
    {
    NSLog(@”反geo检索发送失败”);
    }

}//定位成功,获得经纬度

-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch )searcher result:(BMKReverseGeoCodeResult )result errorCode:(BMKSearchErrorCode)error
{

if (error == 0) {

    //如果定位成功并检索到城市信息,那么就停止定位
    if (result.addressDetail.city != nil) {

        //停止定位
        [_locationService stopUserLocationService];

        NSLog(@"省%@---市%@----区%@--街%@---号%@",result.addressDetail.province,result.addressDetail.city,result.addressDetail.district,result.addressDetail.streetName,result.addressDetail.streetNumber);



}

}

}//获得城市信息

  • (void)didFailToLocateUserWithError:(NSError *)error
    {

    //定位失败的处理(例如:给默认值什么的…)

}//定位失败

注意 : 这里要说明的是,定位不到(网络或者说其它原因),或者用户不允许定位,都是调用代理方法定位失败

你可能感兴趣的:(iOS定位,百度地图定位)