项目中用到了百度地图定位和导航功能,如果将导航代码直接加到需要导航的controller中,无疑该controller的代码会很多,所以需要将地图的功能封装到一个类中,需要用到的时候,在controller中写几句代码就解决了。
以下讲解的前提是顺利集成百度地图和导航情况,如未顺利集成SDK,请移步百度地图开放平台。
1、创建一个名字叫BaseMapView的类
在类的.m文件中写入一下代码
- (instancetype)initWithFrame:(CGRect)frame{
if([superinitWithFrame:frame]){
[self loadMapView];
}
return self;
}
- (void)loadMapView{
_mapView = [[BMKMapView alloc]initWithFrame:self.bounds];
_mapView.delegate = self;
[self addSubview:_mapView];
[self loadLocation];
}
- (void)loadLocation{
//开始定位
_locationService = [[BMKLocationService alloc] init];
_locationService.delegate = self;
[_locationService startUserLocationService];
}
#pragma mark 开始定位
- (void)didUpdateBMKUserLocation:(BMKUserLocation*)userLocation{
//获取当前的位置信息,定位结束
[_locationService stopUserLocationService];
//定位开始
//--------将当前的位置的经纬度转换为文字地址------------
_geoCodeSearch = [[BMKGeoCodeSearch alloc]init];
_geoCodeSearch.delegate = self;
//初始化逆地理编码类
BMKReverseGeoCodeSearchOption *reverseGeoCodeOption= [[BMKReverseGeoCodeSearchOption alloc] init];
//需要逆地理编码的坐标位置
reverseGeoCodeOption.location= userLocation.location.coordinate;
[_geoCodeSearchreverseGeoCode:reverseGeoCodeOption];
}
#pragma amrk 反地理编码的代理方法
- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch*)searcher result:(BMKReverseGeoCodeSearchResult*)result errorCode:(BMKSearchErrorCode)error{
//BMKReverseGeoCodeResult是编码的结果,包括地理位置,道路名称,uid,城市名等信息
BMKAddressComponent*address = result.addressDetail;
NSString *str = [NSString stringWithFormat:@"--%@--%@--%@--%@",address.province,address.city,address.district,address.streetName];
}
#pragma mark - 导航
-(void)routePlanAndNavigation:(NSDictionary*)dic{
if ( [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"baidumap://"]]){
//地理编码器
// ClinicNewModel *model = self.dataArr[index];
NSString*destinationStr =@"天安门";
// NSString *urlString = [[NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=name:%@|latlng:%f,%f&mode=driving",destinationStr,[model.Latitude floatValue],[model.Longitude floatValue]] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *urlString = [[NSString stringWithFormat:@"baidumap://map/direction?origin={{我的位置}}&destination=name:%@|latlng:%f,%f&mode=driving",destinationStr,39.9,116.4] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL*url = [NSURLURLWithString:urlString];
if(@available(iOS10.0, *)) {
[[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
}];
}else{
// Fallback on earlier versions
[[UIApplication sharedApplication] openURL:url];
}
}else{
[self naviGo];
}
}
- (void)naviGo{
double latitude = _userLocation.location.coordinate.latitude;
double longitude = _userLocation.location.coordinate.longitude;
//节点数组
NSMutableArray *nodesArray = [[NSMutableArray alloc] initWithCapacity:2];
//起点
BNRoutePlanNode *startNode = [[BNRoutePlanNode alloc] init];
startNode.pos= [[BNPositionalloc]init];
startNode.pos.x= longitude;
startNode.pos.y= latitude;
startNode.pos.eType = BNCoordinate_BaiduMapSDK;
[nodesArrayaddObject:startNode];
//终点
BNRoutePlanNode *endNode = [[BNRoutePlanNode alloc] init];
endNode.pos= [[BNPositionalloc]init];
endNode.pos.x=116.4;
endNode.pos.y=39.9;
endNode.pos.eType = BNCoordinate_BaiduMapSDK;
[nodesArrayaddObject:endNode];
//发起路径规划
// [BNCoreServices_RoutePlan setDisableOpenUrl:YES];
[BNCoreServices_RoutePlan startNaviRoutePlan:BNRoutePlanMode_Recommend naviNodes:nodesArray time:nil delegete:self userInfo:nil];
}
#pragma mark BNNaviUIManagerDelegate 算路成功回调
-(void)routePlanDidFinished:(NSDictionary*)userInfo{
NSLog(@"算路成功");
//路径规划成功,开始导航 BN_NaviTypeSimulator 默认模拟导航,BN_NaviTypeReal 真机导航
[BNCoreServices_UI showPage:BNaviUI_NormalNavi delegate:self extParams:nil];
}
//算路失败回调
- (void)routePlanDidFailedWithError:(NSError*)error andUserInfo:(NSDictionary*)userInfo{
NSLog(@"算路失败--%@",error);
switch([errorcode]%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(@"算路取消");
}
#pragma mark - 安静退出导航
- (void)exitNaviUI{
[BNCoreServices_UI exitPage:EN_BNavi_ExitTopVC animated:YES extraInfo:nil];
}
#pragma mark BNNaviUIManagerDelegate
//退出导航页面回调
- (void)onExitPage:(BNaviUIType)pageType extraInfo:(NSDictionary*)extraInfo{
if(pageType ==BNaviUI_NormalNavi){
NSLog(@"退出导航");
}elseif(pageType ==BNaviUI_Declaration){
NSLog(@"退出导航声明页面");
}
}
以上代码从百度地图文档也可以看到。
这样一个新的地图类就新建完成,下一步就是使用BaseMapView类进行定位和导航。
2、在ViewController中使用BaseMapView类
- (void)viewDidLoad {
[super viewDidLoad];
_naviView = [[BaseMapView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 200)];
[self.view addSubview:_naviView];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent*)event{
[_naviView routePlanAndNavigation:nil];
}
如此简洁的代码运用了BaseMapView类进行导航,那么重点来了!!!
如果这样就可以导航的话,就不存在这篇文章了!!!
运行后,有如下情况:
百度地图提示算路成功,但是导航页面并不出现,并且控制台打印
Warning: Attempt to present on whose view is not in the window hierarchy!
从网上查了好几个答案,都是这样说的在导航页面.m中增加 -(id)naviPresentedViewController { return self; }
但是无论是在BaseMapView的.m文件还是ViewController的.m文件以上代码,导航页面依然不出现。
真正的解决办法就是在BaseMapView的.m文件中,加
-(id)naviPresentedViewController {
return 此处返回的应该是BaseMapView类所在的controller;
}
上述情况是发生在手机上未安装百度地图app情况下,如果手机上安装了百度地图app,则进行百度的时候,app会自动跳转百度地图app,不会出现上述情况。
有问题可以留言,小编集成过很多次百度地图SDK,每次都会遇到点问题,欢迎iOS开发交流。