iOS 百度定位实现

  • Post author:
  • Post category:其他


1. 导入baiduSDK框架 (BaiduMapAPI_Base.framework,BaiduMapAPI_Location.framework 及其他可能要求的框架库)

添加CoreLocation.framework systemConfiguration.framework libsqlite3.dylib , coreTelephony.framework

将其中任意一个文件改为.mm

在info.plist中添加Bundle display name 与app名称一样即可

在appdelegate中添加

#import <BaiduMapAPI_Base/BMKMapManager.h>


@property (nonatomic, strong) BMKMapManager *manager;


@synthesize manager;


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    // 启动定位管理
    manager = [[BMKMapManager alloc] init];
    BOOL ret = [manager start:@"vzucj3HmQhlzXTPEGtMlWPf3" generalDelegate:nil];
    if (!ret) {
        NSLog(@"定位服务启动失败");
    } else {
        NSLog(@"定位服务启动成功");
        //        启动成功
    }
}

// 在要使用的类中如下处理

#import <BaiduMapAPI_Location/BMKLocationService.h>


@property(nonatomic,retain) BMKLocationService *service;


添加代理:<BMKLocationServiceDelegate>


/**
 *  开启定位
 *
 *  @param webview <#webview description#>
 */
- (void)sendMylocationFromWebView:(UIWebView *)webview {
    if (!_service) {
        _service = [[BMKLocationService alloc] init];
        _service.delegate = self;
    }
    // 启动LocationService
    [_service startUserLocationService];
    self.tempWebView = webview;
}




#pragma mark - 定位代理
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation {
//    NSLog(@"更新了地址位置");
    CLLocation *location = userLocation.location;
    CLLocationCoordinate2D coordinate = location.coordinate;
    DEBUGLog(@"%f,%f",coordinate.latitude,coordinate.longitude);
    [self.service stopUserLocationService];
    
    // 在此处将信息发送过去
    NSString *funcStr = [NSString stringWithFormat:@"locationCall(%f, %f, %f)",coordinate.latitude,coordinate.longitude,0.0];
    NSString *responseStr = [self.tempWebView stringByEvaluatingJavaScriptFromString:funcStr];
//    DEBUGLog(@"返回的字符串为%@",responseStr);
}


- (void)didFailToLocateUserWithError:(NSError *)error {
    DEBUGLog(@"定位错误:%@",error);
//    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.layer.cornerRadius = 5.0;
    btn.clipsToBounds = YES;
    
}

此时并不会显示数据,需要处理:

1. 需要在plist文件中NSLocationAlwaysUsageDescription 设置为YES即可.

如果出现定位错误:Error Domain=kCLErrorDomain Code=0 “The operation couldn’t be completed. (kCLErrorDomain error 0.)”

则需要再进一步配置:

2. 添加模拟器默认位置即可。模拟器->Debug->Location->随便选择一个

3. 针对ios9下不能使用的情况需要在plist文件中添加:NSLocationWhenInUseUsageDescription YES

:Error Domain=kCLErrorDomain Code=0 “(null)”

需要在edit schem中Options设置一下打开地址位置即可



版权声明:本文为linfengwenyou原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。