[iOS]百度地图整理

开发者可在百度地图iOS SDK的下载页面下载到最新版的地图SDK,下载地址为:http://developer.baidu.com/map/index.php?title=iossdk/sdkiosdev-download

1.申请密钥

百度地图iOS SDK开发密钥的申请地址为:http://lbsyun.baidu.com/apiconsole/key

2.配置开发环境

2.1、根据需要导入 .framework包

百度地图 iOS SDK 采用分包的形式提供 .framework包,请广大开发者使用时确保各分包的版本保持一致。其中BaiduMapAPI_Base.framework为基础包,使用SDK任何功能都需导入,其他分包可按需导入。
将所需的BaiduMapAPI_.framework拷贝到工程所在文件夹下。
在 TARGETS->Build Phases-> Link Binary With Libaries中点击“+”按钮,在弹出的窗口中点击“Add Other”按钮,选择BaiduMapAPI_.framework添加到工程中。
注: 静态库中采用Objective-C++实现,因此需要您保证您工程中至少有一个**.mm**后缀的源文件(您可以将任意一个.m后缀的文件改名为.mm),或者在工程属性中指定编译方式,即在Xcode的Project -> Edit Active Target -> Build Setting 中找到 Compile Sources As,并将其设置为**"Objective-C++"**

2.2、引入所需的系统库

百度地图SDK中提供了定位功能和动画效果,v2.0.0版本开始使用OpenGL渲染,因此您需要在您的Xcode工程中引入
CoreLocation.framework
QuartzCore.framework
OpenGLES.framework
SystemConfiguration.framework
CoreGraphics.framework
Security.framework
libsqlite3.0.tbd(xcode7以前为 libsqlite3.0.dylib)
CoreTelephony.framework
libstdc++.6.0.9.tbd(xcode7以前为libstdc++.6.0.9.dylib)

:加粗标识的系统库为v2.9.0新增的系统库,使用v2.9.0及以上版本的地图SDK,务必增加导入这3个系统库。)
添加方式:在Xcode的Project -> Active Target ->Build Phases ->Link Binary With Libraries,添加这几个系统库即可。

[iOS]百度地图整理_第1张图片

2.3、引入mapapi.bundle资源文件

如果使用了基础地图功能,需要添加该资源,否则地图不能正常显示mapapi.bundle中存储了定位、默认大头针标注View及路线关键点的资源图片,还存储了矢量地图绘制必需的资源文件。如果您不需要使用内置的图片显示功能,则可以删除bundle文件中的image文件夹。您也可以根据具体需求任意替换或删除该bundle中image文件夹的图片文件。方法:选中工程名,在右键菜单中选择Add Files to “工程名”…,从BaiduMapAPI_Map.framework||Resources文件中选择mapapi.bundle文件,并勾选“Copy items if needed”复选框,单击“Add”按钮,将资源文件添加到工程中。

2.4、环境配置

1)如果您只在Xib文件中使用了BMKMapView,没有在代码中使用BMKMapView,编译器在链接时不会链接对应符号,需要在工程属性中显式设定:在Xcode的Project -> Edit Active Target -> Build Setting -> Other Linker Flags中添加-ObjC
2)由于iOS9改用更安全的https,为了能够在iOS9中正常使用地图SDK,请在"Info.plist"中进行如下配置,否则影响SDK的使用。

NSAppTransportSecurity NSAllowsArbitraryLoads ```

3)如果在iOS9中使用了调起百度地图客户端功能,必须在"Info.plist"中进行如下配置,否则不能调起百度地图客户端。
![](http://upload-images.jianshu.io/upload_images/2023270-8b135cff462ad201.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

LSApplicationQueriesSchemes baidumap```

2.5、引入头文件

在使用SDK的类 按需 引入下边的头文件:

#import //引入base相关所有的头文件
#import //引入地图功能所有的头文件
#import //引入检索功能所有的头文件
#import //引入云检索功能所有的头文件
#import //引入定位功能所有的头文件
#import //引入计算工具所有的头文件
#import //引入周边雷达功能所有的头文件
#import < BaiduMapAPI_Map/BMKMapView.h>//只引入所需的单个头文件```

#3、相关代码
#3.1管理地图的生命周期
自2.0.0起,BMKMapView新增viewWillAppear、viewWillDisappear方法来控制BMKMapView的生命周期,并且在一个时刻只能有一个BMKMapView接受回调消息,因此在使用BMKMapView的viewController中需要在viewWillAppear、viewWillDisappear方法中调用BMKMapView的对应的方法,并处理delegate,代码如下:

-(void)viewWillAppear:(BOOL)animated {
[_mapView viewWillAppear];
_mapView.delegate = self; // 此处记得不用的时候需要置nil,否则影响内存的释放
}

-(void)viewWillDisappear:(BOOL)animated {
[_mapView viewWillDisappear];
_mapView.delegate = nil; // 不用时,置nil
}```

3.2 使用百度地图,启动BaiduMapManager

2)在AppDelegate里操作:

@interface AppDelegate : NSObject { BMKMapManager* _mapManager;}```

@implementation AppDelegate- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// 1.创建窗口
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
// 2.设置窗口的根控制器
[self.window switchRootViewController];
// 3.显示窗口
[self.window makeKeyAndVisible];
float version = [[[UIDevice currentDevice] systemVersion] floatValue];
if (version >= 8.0) {
// iOS8+ IconBadge需授权
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge categories:nil];

[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
}
// 要使用百度地图,请先启动
BaiduMapManager _mapManager = [[BMKMapManager alloc]init];
// 如果要关注网络及授权验证事件,请设定generalDelegate参数
BOOL ret = [_mapManager start:BaiduMapAppKey generalDelegate:self];
if (!ret) {
NSLog(@"manager start failed!");
}
return YES;
}```

4、定位功能及反地理编码出地理位置

1)自iOS SDK v2.5.0起,为了对iOS8的定位能力做兼容,做了相应的修改,开发者在使用过程中注意事项如下:

需要在info.plist里添加(以下二选一,两个都添加默认使用
NSLocationWhenInUseUsageDescription):
NSLocationWhenInUseUsageDescription ,允许在前台使用时获取GPS的描述
NSLocationAlwaysUsageDescription ,允许永久使用GPS的描述```

![](http://upload-images.jianshu.io/upload_images/2023270-e1e5ae4e6eebe331.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
2)部分代码如下:

@interface QTXHomeController (){
BMKLocationService *_locService;
BMKGeoCodeSearch *_geoCodeSearch;
}```

- (void)viewDidLoad { 
[super viewDidLoad]; // 设置地图定位
 [self setupBMKLocation];
}
#pragma mark - BMKLocationService- (void)setupBMKLocation { 
//初始化
BMKLocationService _locService = [[BMKLocationService alloc]init]; 
  _locService.delegate = self; // 初始化编码服务
   _geoCodeSearch = [[BMKGeoCodeSearch alloc] init]; 
  _geoCodeSearch.delegate = self; //启动
  LocationService [_locService startUserLocationService];
}
-(void)viewWillAppear:(BOOL)animated { 
  [super viewWillAppear:animated];
   _locService.delegate = self;
}
-(void)viewWillDisappear:(BOOL)animated { 
  [super viewWillDisappear:animated]; 
  _locService.delegate = nil;
}
#pragma mark - BMKLocationServiceDelegate 实现相关delegate 处理位置信息更新
/** *在地图View将要启动定位时,会调用此函数 *@param mapView 地图View */
- (void)willStartLocatingUser{ 
NSLog(@"start locate");
}
/** *用户方向更新后,会调用此函数 *@param userLocation 新的用户位置 */
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation{ 
  NSLog(@"heading is %@",userLocation.heading);
}
/** *用户位置更新后,会调用此函数 *@param userLocation 新的用户位置 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation{ 
  NSLog(@"didUpdateUserLocation lat %f,long %f", userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude);
 //反地理编码出地理位置 
CLLocationCoordinate2D pt =(CLLocationCoordinate2D){0,0}; 
pt = (CLLocationCoordinate2D){userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude}; 
BMKReverseGeoCodeOption *reverseGeoCodeOption =[[BMKReverseGeoCodeOption alloc] init]; reverseGeoCodeOption.reverseGeoPoint = pt; 
//发送反编码请求.并返回是否成功 
BOOL flag = [_geoCodeSearch reverseGeoCode:reverseGeoCodeOption]; 
if (flag) { 
NSLog(@"反geo检索发送成功");
 } else { 
NSLog(@"反geo检索发送失败");
 } // 停止定位 
[_locService stopUserLocationService];
}
/** *在地图View停止定位后,会调用此函数 *@param mapView 地图View */
- (void)didStopLocatingUser{ 
NSLog(@"stop locate");
}
/** *定位失败后,会调用此函数 *@param mapView 地图View *@param error 错误号,参考CLError.h中定义的错误号 */
- (void)didFailToLocateUserWithError:(NSError *)error{ 
  NSLog(@"location error"); 
  NSString *city = [[NSUserDefaults standardUserDefaults] objectForKey:@"cityNmae"];
   [self.cityBtn setTitle:city forState:UIControlStateNormal];
}
// 反地理编码
- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error { 

if (error == 0) { 
NSString *cityName = [result.poiList.firstObject city]; 
NSLog(@"dic:%@ , dic[cityName]:%@", dic, dic[cityName]); 
NSLog(@"%@, %@", [result.poiList.firstObject city], result.address); 

// 定位城市后本地偏好设置存储当前城市编码cityCode后,需要同步 
[[NSUserDefaults standardUserDefaults] setObject:self.cityCode forKey:@"cityCode"]; 
[[NSUserDefaults standardUserDefaults] synchronize]; 

// 定位的city
 [[NSUserDefaults standardUserDefaults] setObject:[result.poiList.firstObject city] forKey:@"city"];
 [[NSUserDefaults standardUserDefaults] synchronize]; 

// 保存定位的街道地址
 [[NSUserDefaults standardUserDefaults] setObject:result.addressDetail.streetName forKey:@"street"];
 [[NSUserDefaults standardUserDefaults] synchronize]; 
  }
}```

#5.打开地图界面 规划路线
相关代码如下:

import

@interface QTXPlanningRouteMapController : UIViewController
{
BMKRouteSearch * _routesearch;
}
@property (nonatomic, copy) NSString *address;

@end```

#import "QTXPlanningRouteMapController.h"
#import 
#import 
#import 
#import "QTXRouteAnnotation.h"
@interface QTXPlanningRouteMapController ()  
{ 
BMKMapView * _mapView; 
BMKLocationService *_locService; 
BMKGeoCodeSearch *_geoCodeSearch;
}
@property (nonatomic, strong) BMKUserLocation *userLocation;
@end
@implementation QTXPlanningRouteMapController
-(void)viewDidLoad {
 [super viewDidLoad];
}
-(void)viewWillAppear:(BOOL)animated { 
[super viewWillAppear:animated]; 
_routesearch = [[BMKRouteSearch alloc]init]; 
_mapView.delegate = self; // 此处记得不用的时候需要置nil,否则影响内存的释放 
_routesearch.delegate = self; // 此处记得不用的时候需要置nil,否则影响内存的释放 
// 开始定位 
[self mapLocationClick];
}
-(void)viewWillDisappear:(BOOL)animated {
 [super viewWillDisappear:animated];
 _mapView.delegate = nil; // 不用时,置nil 
_routesearch.delegate = nil; // 不用时,置nil 
// 停止定位
// [_locService stopUserLocationService]; 
_mapView.showsUserLocation = NO;
}
- (void)dealloc {
 if (_routesearch != nil) {
 _routesearch = nil; 
}
 if (_mapView) { 
_mapView = nil; 
}
}
- (void)mapLocationClick { 
// 创建一张百度地图 
// 1.首先接受基本的地图功能
 _mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 0, UI_View_Width, UI_View_Height)]; 
_mapView.delegate = self; 
[self.view addSubview:_mapView];
 // 2.开始定位
// _locService = [[BMKLocationService alloc]init];
// [_locService startUserLocationService];
 _mapView.showsUserLocation = NO;//先关闭显示的定位图层 _mapView.userTrackingMode = BMKUserTrackingModeNone;//设置定位的状态 _mapView.showsUserLocation = YES;//显示定位图层 _mapView.showsUserLocation = YES; //显示定位图层(即我的位置的小圆点) [_mapView setZoomLevel:14]; //地图显示比例 
// [_mapView setMapType:BMKMapTypeStandard];
//设置地图为标准类型
 // _mapView.rotateEnabled = NO; 
//设置是否可以旋转
// [self onGeoSearch];
}
#pragma mark - BMKMapViewDelegate
- (BMKAnnotationView *)mapView:(BMKMapView *)view viewForAnnotation:(id )annotation{
 if ([annotation isKindOfClass:[QTXRouteAnnotation class]]) {
 return [self getQTXRouteAnnotationView:view viewForAnnotation:(QTXRouteAnnotation*)annotation]; 
}
 return nil;
}
- (BMKOverlayView*)mapView:(BMKMapView *)map viewForOverlay:(id)overlay{
 if ([overlay isKindOfClass:[BMKPolyline class]]) { 
BMKPolylineView* polylineView = [[BMKPolylineView alloc] initWithOverlay:overlay]; 
polylineView.fillColor = [[UIColor alloc] initWithRed:0 green:1 blue:1 alpha:1]; 
polylineView.strokeColor = [[UIColor alloc] initWithRed:0 green:0 blue:1 alpha:0.7]; 
polylineView.lineWidth = 3.0; return polylineView;
 } 
return nil;
}
- (BMKAnnotationView*)getQTXRouteAnnotationView:(BMKMapView *)mapview viewForAnnotation:(QTXRouteAnnotation*)QTXRouteAnnotation{ 
BMKAnnotationView* view = nil; 
switch (QTXRouteAnnotation.type) { 
case 0: { view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"start_node"]; 
if (view == nil) { 
view = [[BMKAnnotationView alloc]initWithAnnotation:QTXRouteAnnotation reuseIdentifier:@"start_node"]; 
view.image = [UIImage imageNamed:@"icon_nav_start"]; 
view.centerOffset = CGPointMake(0, -(view.frame.size.height * 0.5)); 
view.canShowCallout = TRUE; 
} 
view.annotation = QTXRouteAnnotation;
 } 
break; 
case 1: { 
view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"end_node"]; 
if (view == nil) { 
view = [[BMKAnnotationView alloc]initWithAnnotation:QTXRouteAnnotation reuseIdentifier:@"end_node"]; 
view.image = [UIImage imageNamed:@"icon_nav_end"]; 
view.centerOffset = CGPointMake(0, -(view.frame.size.height * 0.5)); 
view.canShowCallout = TRUE;
 }
 view.annotation = QTXRouteAnnotation; 
}
 break; 
case 2: { 
view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"bus_node"]; 
if (view == nil) { 
view = [[BMKAnnotationView alloc]initWithAnnotation:QTXRouteAnnotation reuseIdentifier:@"bus_node"]; 
view.image = [UIImage imageNamed:@"icon_nav_bus"]; 
view.canShowCallout = TRUE;
 } 
view.annotation = QTXRouteAnnotation; 
} 
break; 
case 3: { 
view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"rail_node"]; 
if (view == nil) { view = [[BMKAnnotationView alloc]initWithAnnotation:QTXRouteAnnotation reuseIdentifier:@"rail_node"]; 
view.image = [UIImage imageNamed:@"icon_nav_rail"]; 
view.canShowCallout = TRUE; 
} 
view.annotation = QTXRouteAnnotation; 
} 
break; 
case 4: { 
view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"route_node"]; 
if (view == nil) { 
view = [[BMKAnnotationView alloc]initWithAnnotation:QTXRouteAnnotation reuseIdentifier:@"route_node"]; 
view.canShowCallout = TRUE;
 } else { 
[view setNeedsDisplay];
 } UIImage* image = [UIImage imageNamed:@"icon_direction"]; 
view.image = [image imageRotatedByDegrees:QTXRouteAnnotation.degree]; 
view.annotation = QTXRouteAnnotation; 
} 
break;
 // case 5: 
// { 
// view = [mapview dequeueReusableAnnotationViewWithIdentifier:@"waypoint_node"]; 
// if (view == nil) {
 // view = [[BMKAnnotationView alloc]initWithAnnotation:QTXRouteAnnotation reuseIdentifier:@"waypoint_node"]; 
// view.canShowCallout = TRUE; 
// } else { 
// [view setNeedsDisplay]; 
// }
 //
 // UIImage* image = [UIImage imageWithContentsOfFile:[self getMyBundlePath1:@"images/icon_nav_waypoint.png"]]; 
// view.image = [image imageRotatedByDegrees:QTXRouteAnnotation.degree]; 
// view.annotation = QTXRouteAnnotation;
 // } 
// break; 
default: break; 
} 
return view;
}
#pragma mark - BMKRouteSearchDelegate
- (void)onGetTransitRouteResult:(BMKRouteSearch*)searcher result:(BMKTransitRouteResult*)result errorCode:(BMKSearchErrorCode)error{ 
NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
 [_mapView removeAnnotations:array]; 
array = [NSArray arrayWithArray:_mapView.overlays];
 [_mapView removeOverlays:array]; 
if (error == BMK_SEARCH_NO_ERROR) { 
BMKTransitRouteLine* plan = (BMKTransitRouteLine*)[result.routes objectAtIndex:0];
 // 计算路线方案中的路段数目 
NSInteger size = [plan.steps count]; 
int planPointCounts = 0;
 for (int i = 0; i < size; i++) { 
BMKTransitStep* transitStep = [plan.steps objectAtIndex:i]; 
if(i==0){ 
QTXRouteAnnotation* item = [[QTXRouteAnnotation alloc]init]; 
item.coordinate = plan.starting.location; 
item.title = @"起点"; item.type = 0; 
[_mapView addAnnotation:item];
 // 添加起点标注 
}else if(i==size-1){ 
QTXRouteAnnotation* item = [[QTXRouteAnnotation alloc]init];
 item.coordinate = plan.terminal.location; item.title = @"终点"; 
item.type = 1;
 [_mapView addAnnotation:item]; 
// 添加起点标注 
} 
QTXRouteAnnotation* item = [[QTXRouteAnnotation alloc]init]; item.coordinate = transitStep.entrace.location;
 item.title = transitStep.instruction; item.type = 3;
 [_mapView addAnnotation:item]; 
//轨迹点总数累计 
planPointCounts += transitStep.pointsCount;
 }
 //轨迹点 
BMKMapPoint * temppoints = new BMKMapPoint[planPointCounts];
 int i = 0; for (int j = 0; j < size; j++) { 
BMKTransitStep* transitStep = [plan.steps objectAtIndex:j];
 int k=0;
 for(k=0;k rbX) { rbX = pt.x; } 
if (pt.y > ltY) { ltY = pt.y; }
 if (pt.y < rbY) { rbY = pt.y; } } 
BMKMapRect rect; 
rect.origin = BMKMapPointMake(ltX , ltY); 
rect.size = BMKMapSizeMake(rbX - ltX, rbY - ltY); 
[_mapView setVisibleMapRect:rect]; 
_mapView.zoomLevel = _mapView.zoomLevel - 0.3;}
#pragma mark - 百度地图 大头针图像扩展(旋转效果)
- (UIImage*)imageRotatedByDegrees:(CGFloat)degrees{ 
CGFloat width = CGImageGetWidth(self.CGImage); 
CGFloat height = CGImageGetHeight(self.CGImage); 
CGSize rotatedSize; rotatedSize.width = width;
 rotatedSize.height = height; 
UIGraphicsBeginImageContext(rotatedSize); 
CGContextRef bitmap = UIGraphicsGetCurrentContext(); CGContextTranslateCTM(bitmap, rotatedSize.width/2, rotatedSize.height/2); CGContextRotateCTM(bitmap, degrees * M_PI / 180); CGContextRotateCTM(bitmap, M_PI); CGContextScaleCTM(bitmap, -1.0, 1.0); CGContextDrawImage(bitmap, CGRectMake(-rotatedSize.width/2, -rotatedSize.height/2, rotatedSize.width, rotatedSize.height), self.CGImage); UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();
 return newImage;
}
@end

// 步行路线规划
-(void)onClickWalkSearch {
 // 起始地址
 BMKPlanNode *start = [[BMKPlanNode alloc]init]; 
start.name = [[NSUserDefaults standardUserDefaults] objectForKey:@"street"]; 
start.cityName = [[NSUserDefaults standardUserDefaults] objectForKey:@"city"]; 
//
 结束地址 
BMKPlanNode *end = [[BMKPlanNode alloc]init]; end.name = self.address; 
end.cityName = [[NSUserDefaults standardUserDefaults] objectForKey:@"cityName"]; 
BMKWalkingRoutePlanOption *walkingRouteSearchOption = [[BMKWalkingRoutePlanOption alloc]init]; 
walkingRouteSearchOption.from = start; 
walkingRouteSearchOption.to = end; 
BOOL flag = [_routesearch walkingSearch:walkingRouteSearchOption];
 if(flag) { NSLog(@"walk检索发送成功"); 
} else { 
NSLog(@"walk检索发送失败");
 }
}
// 公交路线规划
-(void)onClickBusSearch { 
// 起始地址 
BMKPlanNode *start = [[BMKPlanNode alloc]init]; 
start.name = [[NSUserDefaults standardUserDefaults] objectForKey:@"street"]; 
start.cityName = [[NSUserDefaults standardUserDefaults] objectForKey:@"city"]; 
// 结束地址 
BMKPlanNode *end = [[BMKPlanNode alloc]init]; end.name = self.address; 
end.cityName = [[NSUserDefaults standardUserDefaults] objectForKey:@"cityName"]; 
BMKTransitRoutePlanOption *transitRouteSearchOption = [[BMKTransitRoutePlanOption alloc]init];
 transitRouteSearchOption.city= [[NSUserDefaults standardUserDefaults] objectForKey:@"cityName"]; 
transitRouteSearchOption.from = start;
 transitRouteSearchOption.to = end;
 BOOL flag = [_routesearch transitSearch:transitRouteSearchOption]; 
if(flag) { NSLog(@"bus检索发送成功"); 
} else { 
NSLog(@"bus检索发送失败");
 }
}
// 驾车路线规划
-(void)onClickCarSearch {
 // 起始地址 
BMKPlanNode *start = [[BMKPlanNode alloc]init]; 
start.name = [[NSUserDefaults standardUserDefaults] objectForKey:@"street"]; 
start.cityName = [[NSUserDefaults standardUserDefaults] objectForKey:@"city"];
 // 结束地址 
BMKPlanNode *end = [[BMKPlanNode alloc]init]; 
end.name = self.address; 
end.cityName = [[NSUserDefaults standardUserDefaults] objectForKey:@"cityName"]; 
BMKDrivingRoutePlanOption *drivingRouteSearchOption = [[BMKDrivingRoutePlanOption alloc]init]; 
drivingRouteSearchOption.from = start; 
drivingRouteSearchOption.to = end; 
BOOL flag = [_routesearch drivingSearch:drivingRouteSearchOption];
 if(flag) { NSLog(@"car检索发送成功"); 
} else { 
NSLog(@"car检索发送失败"); 
}
}```
![](http://upload-images.jianshu.io/upload_images/2023270-78a42cce0a45814d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)驾车.png

![](http://upload-images.jianshu.io/upload_images/2023270-b4d71ab864d72a36.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)公交.jpg

![](http://upload-images.jianshu.io/upload_images/2023270-c7e31da9a53fc4ea.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)步行.jpg

#6.打开地图界面 大头针定位
相关代码如下:

import

@interface QTXOpenMapController : UIViewController {
BMKMapManager *_mapManager;
BMKLocationService *_locService;
BMKMapView *_mapView;
}
@end```

#import "QTXOpenMapController.h"
@interface QTXOpenMapController ()  { 
bool isGeoSearch; 
BMKGeoCodeSearch* _geocodesearch;
}
@property (nonatomic, weak) BMKPointAnnotation *annotation;
@property (nonatomic, copy) NSString *address;
@property (nonatomic, assign) CLLocationCoordinate2D coor;
@property (nonatomic, strong) BMKUserLocation *userLocation;
@end
@implementation QTXOpenMapController
- (void)viewDidLoad {
 [super viewDidLoad];
 _geocodesearch = [[BMKGeoCodeSearch alloc]init]; 
_geocodesearch.delegate = self; // 此处记得不用的时候需要置nil,否则影响内存的释放 
// 开始定位
 [self mapLocationClick];
}
- (void)backClick { 
// 停止定位 
[_locService stopUserLocationService];
 _mapView.showsUserLocation = NO; 
[self.navigationController popViewControllerAnimated:YES];
}
- (void)mapLocationClick { 
// 创建一张百度地图
 // 1.首先接受基本的地图功能 
_mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 0, UI_View_Width, UI_View_Height)]; 
_mapView.delegate = self;
 [self.view addSubview:_mapView]; 
// 2.开始定位 
_locService = [[BMKLocationService alloc]init];
 [_locService startUserLocationService]; 
_mapView.showsUserLocation = NO;//先关闭显示的定位图层 
_mapView.userTrackingMode = BMKUserTrackingModeNone;//设置定位的状态 
_mapView.showsUserLocation = YES;//显示定位图层 
_mapView.showsUserLocation = YES; //显示定位图层(即我的位置的小圆点) 
[_mapView setZoomLevel:14]; //地图显示比例 
[self onGeoSearch];
}
-(void)viewWillAppear:(BOOL)animated {
 [_mapView viewWillAppear];
 _mapView.delegate = self; // 此处记得不用的时候需要置nil,否则影响内存的释放 
_locService.delegate = self; // 大头针 
BMKPointAnnotation *annotation = [[BMKPointAnnotation alloc] init];
 [_mapView addAnnotation:annotation]; 
self.annotation = annotation;
}
-(void)viewWillDisappear:(BOOL)animated {
 [_mapView viewWillDisappear];
 _mapView.delegate = nil; // 不用时,置nil 
_locService.delegate = nil;
}
/** *在地图View将要启动定位时,会调用此函数 *@param mapView 地图View */
- (void)willStartLocatingUser{ 
NSLog(@"start locate");
}
/** *用户方向更新后,会调用此函数 *@param userLocation 新的用户位置 */
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation{ 
[_mapView updateLocationData:userLocation]; 
NSLog(@"heading is %@",userLocation.heading);
}
/** *用户位置更新后,会调用此函数 *@param userLocation 新的用户位置 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation{ NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude); 
self.userLocation = userLocation;
 [_mapView updateLocationData:userLocation];
}
/** *在地图View停止定位后,会调用此函数 *@param mapView 地图View */
- (void)didStopLocatingUser{ 
NSLog(@"stop locate");
}
/** *定位失败后,会调用此函数 *
@param mapView 地图View *
@param error 错误号,参考CLError.h中定义的错误号 */
- (void)didFailToLocateUserWithError:(NSError *)error{ 
NSLog(@"location error");
}
- (void)dealloc { 
if (_mapView) {
 _mapView = nil;
 }
}
#pragma mark - BMKMapViewDelegate
- (void)mapViewDidFinishLoading:(BMKMapView *)mapView {
// UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"地图初始化完成" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles: nil];
// [alert show];
// alert = nil;
// 
// 开始地理编码
// [self onClickGeocode];}
- (void)mapView:(BMKMapView *)mapView onClickedMapBlank:(CLLocationCoordinate2D)coordinate { 
NSLog(@"map view: click blank");
}
- (void)mapview:(BMKMapView *)mapView onDoubleClick:(CLLocationCoordinate2D)coordinate { 
NSLog(@"map view: double click");
}
#pragma mark -传入定位坐标// 设置定位到得用户的位置,这里是简单的应用方法(必须打开程序时已经获取到地理位置坐标,为了解决地图定位时总是先显示天安门)
- (void)passLocationValue:(BMKUserLocation *)userLocation{ 
_mapView.centerCoordinate = userLocation.location.coordinate;
}
// 根据anntation生成对应的View
- (BMKAnnotationView *)mapView:(BMKMapView *)view viewForAnnotation:(id )annotation{ 
NSString *AnnotationViewID = @"annotationViewID"; 
//根据指定标识查找一个可被复用的标注View,一般在delegate中使用,用此函数来代替新申请一个View 
BMKAnnotationView *annotationView = [view dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID]; 
if (annotationView == nil) { 
annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID]; 
((BMKPinAnnotationView*)annotationView).pinColor = BMKPinAnnotationColorRed; 
((BMKPinAnnotationView*)annotationView).animatesDrop = YES; // 设置该标注点动画显示 
} 
annotationView.centerOffset = CGPointMake(0, -(annotationView.frame.size.height * 0.5)); 
annotationView.annotation = annotation; 
annotationView.canShowCallout = TRUE; 
return annotationView;
}
- (void)onGeoSearch { 
isGeoSearch = true; 
BMKGeoCodeSearchOption *geocodeSearchOption = [[BMKGeoCodeSearchOption alloc]init]; 
// 获取城市名称 NSString *cityName = [[NSUserDefaults standardUserDefaults] valueForKey:@"cityName"];
 geocodeSearchOption.city= cityName;
 geocodeSearchOption.address = self.address; 
BOOL flag = [_geocodesearch geoCode:geocodeSearchOption];
 if(flag) { 
NSLog(@"geo检索发送成功");
 } else { 
NSLog(@"geo检索发送失败");
 }}
- (void)onGetGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{ 
NSArray* array = [NSArray arrayWithArray:_mapView.annotations]; 
[_mapView removeAnnotations:array]; 
array = [NSArray arrayWithArray:_mapView.overlays];
 [_mapView removeOverlays:array]; 
if (error == 0) { 
BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init]; 
item.coordinate = result.location;
 item.title = result.address;
 [_mapView addAnnotation:item]; 
_mapView.centerCoordinate = result.location; 
} else { 
_mapView.centerCoordinate = self.userLocation.location.coordinate; 
[MBProgressHUD showError:@"暂无详细地址"]; 
}
}
- (void)didReceiveMemoryWarning { 
[super didReceiveMemoryWarning]; 
// Dispose of any resources that can be recreated.
}
@end```

你可能感兴趣的:([iOS]百度地图整理)