[iOS]百度地圖整理

開發(fā)者可在百度地圖iOS SDK的下載頁(yè)面下載到最新版的地圖SDK,下載地址為:http://developer.baidu.com/map/index.php?title=iossdk/sdkiosdev-download

1.申請(qǐng)密鑰

百度地圖iOS SDK開發(fā)密鑰的申請(qǐng)地址為:http://lbsyun.baidu.com/apiconsole/key

2.配置開發(fā)環(huán)境

2.1、根據(jù)需要導(dǎo)入 .framework包

百度地圖 iOS SDK 采用分包的形式提供 .framework包,請(qǐng)廣大開發(fā)者使用時(shí)確保各分包的版本保持一致。其中BaiduMapAPI_Base.framework為基礎(chǔ)包,使用SDK任何功能都需導(dǎo)入,其他分包可按需導(dǎo)入。
將所需的BaiduMapAPI_.framework拷貝到工程所在文件夾下。
在 TARGETS->Build Phases-> Link Binary With Libaries中點(diǎn)擊“+”按鈕,在彈出的窗口中點(diǎn)擊“Add Other”按鈕,選擇BaiduMapAPI_.framework添加到工程中。
注: 靜態(tài)庫(kù)中采用Objective-C++實(shí)現(xiàn),因此需要您保證您工程中至少有一個(gè)**.mm**后綴的源文件(您可以將任意一個(gè).m后綴的文件改名為.mm),或者在工程屬性中指定編譯方式,即在Xcode的Project -> Edit Active Target -> Build Setting 中找到 Compile Sources As,并將其設(shè)置為**"Objective-C++"**

2.2、引入所需的系統(tǒng)庫(kù)

百度地圖SDK中提供了定位功能和動(dòng)畫效果,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)

:加粗標(biāo)識(shí)的系統(tǒng)庫(kù)為v2.9.0新增的系統(tǒng)庫(kù),使用v2.9.0及以上版本的地圖SDK,務(wù)必增加導(dǎo)入這3個(gè)系統(tǒng)庫(kù)。)
添加方式:在Xcode的Project -> Active Target ->Build Phases ->Link Binary With Libraries,添加這幾個(gè)系統(tǒng)庫(kù)即可。

2.3、引入mapapi.bundle資源文件

如果使用了基礎(chǔ)地圖功能,需要添加該資源,否則地圖不能正常顯示mapapi.bundle中存儲(chǔ)了定位、默認(rèn)大頭針標(biāo)注View及路線關(guān)鍵點(diǎn)的資源圖片,還存儲(chǔ)了矢量地圖繪制必需的資源文件。如果您不需要使用內(nèi)置的圖片顯示功能,則可以刪除bundle文件中的image文件夾。您也可以根據(jù)具體需求任意替換或刪除該bundle中image文件夾的圖片文件。方法:選中工程名,在右鍵菜單中選擇Add Files to “工程名”…,從BaiduMapAPI_Map.framework||Resources文件中選擇mapapi.bundle文件,并勾選“Copy items if needed”復(fù)選框,單擊“Add”按鈕,將資源文件添加到工程中。

2.4、環(huán)境配置

1)如果您只在Xib文件中使用了BMKMapView,沒有在代碼中使用BMKMapView,編譯器在鏈接時(shí)不會(huì)鏈接對(duì)應(yīng)符號(hào),需要在工程屬性中顯式設(shè)定:在Xcode的Project -> Edit Active Target -> Build Setting -> Other Linker Flags中添加-ObjC
2)由于iOS9改用更安全的https,為了能夠在iOS9中正常使用地圖SDK,請(qǐng)?jiān)?Info.plist"中進(jìn)行如下配置,否則影響SDK的使用。

<key>NSAppTransportSecurity</key><dict> <key>NSAllowsArbitraryLoads</key> <true/></dict>```

3)如果在iOS9中使用了調(diào)起百度地圖客戶端功能,必須在"Info.plist"中進(jìn)行如下配置,否則不能調(diào)起百度地圖客戶端。
![](http://upload-images.jianshu.io/upload_images/2023270-8b135cff462ad201.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

<key>LSApplicationQueriesSchemes</key><array> <string>baidumap</string></array>```

2.5、引入頭文件

在使用SDK的類 按需 引入下邊的頭文件:

#import <BaiduMapAPI_Base/BMKBaseComponent.h>//引入base相關(guān)所有的頭文件
#import <BaiduMapAPI_Map/BMKMapComponent.h>//引入地圖功能所有的頭文件
#import <BaiduMapAPI_Search/BMKSearchComponent.h>//引入檢索功能所有的頭文件
#import <BaiduMapAPI_Cloud/BMKCloudSearchComponent.h>//引入云檢索功能所有的頭文件
#import <BaiduMapAPI_Location/BMKLocationComponent.h>//引入定位功能所有的頭文件
#import <BaiduMapAPI_Utils/BMKUtilsComponent.h>//引入計(jì)算工具所有的頭文件
#import <BaiduMapAPI_Radar/BMKRadarComponent.h>//引入周邊雷達(dá)功能所有的頭文件
#import < BaiduMapAPI_Map/BMKMapView.h>//只引入所需的單個(gè)頭文件```

#3、相關(guān)代碼
#3.1管理地圖的生命周期
自2.0.0起,BMKMapView新增viewWillAppear、viewWillDisappear方法來控制BMKMapView的生命周期,并且在一個(gè)時(shí)刻只能有一個(gè)BMKMapView接受回調(diào)消息,因此在使用BMKMapView的viewController中需要在viewWillAppear、viewWillDisappear方法中調(diào)用BMKMapView的對(duì)應(yīng)的方法,并處理delegate,代碼如下:

-(void)viewWillAppear:(BOOL)animated {
[_mapView viewWillAppear];
_mapView.delegate = self; // 此處記得不用的時(shí)候需要置nil,否則影響內(nèi)存的釋放
}

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

3.2 使用百度地圖,啟動(dòng)BaiduMapManager

2)在AppDelegate里操作:

@interface AppDelegate : NSObject <UIApplicationDelegate, BMKGeneralDelegate>{ BMKMapManager* _mapManager;}```

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

[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
}
// 要使用百度地圖,請(qǐng)先啟動(dòng)
BaiduMapManager _mapManager = [[BMKMapManager alloc]init];
// 如果要關(guān)注網(wǎng)絡(luò)及授權(quán)驗(yàn)證事件,請(qǐng)?jiān)O(shè)定generalDelegate參數(shù)
BOOL ret = [_mapManager start:BaiduMapAppKey generalDelegate:self];
if (!ret) {
NSLog(@"manager start failed!");
}
return YES;
}```

4、定位功能及反地理編碼出地理位置

1)自iOS SDK v2.5.0起,為了對(duì)iOS8的定位能力做兼容,做了相應(yīng)的修改,開發(fā)者在使用過程中注意事項(xiàng)如下:

需要在info.plist里添加(以下二選一,兩個(gè)都添加默認(rèn)使用
NSLocationWhenInUseUsageDescription):
NSLocationWhenInUseUsageDescription ,允許在前臺(tái)使用時(shí)獲取GPS的描述
NSLocationAlwaysUsageDescription ,允許永久使用GPS的描述```

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

@interface QTXHomeController ()<BMKLocationServiceDelegate, BMKGeoCodeSearchDelegate>{
BMKLocationService *_locService;
BMKGeoCodeSearch *_geoCodeSearch;
}```

- (void)viewDidLoad { 
[super viewDidLoad]; // 設(shè)置地圖定位
 [self setupBMKLocation];
}
#pragma mark - BMKLocationService- (void)setupBMKLocation { 
//初始化
BMKLocationService _locService = [[BMKLocationService alloc]init]; 
  _locService.delegate = self; // 初始化編碼服務(wù)
   _geoCodeSearch = [[BMKGeoCodeSearch alloc] init]; 
  _geoCodeSearch.delegate = self; //啟動(dòng)
  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 實(shí)現(xiàn)相關(guān)delegate 處理位置信息更新
/** *在地圖View將要啟動(dòng)定位時(shí),會(huì)調(diào)用此函數(shù) *@param mapView 地圖View */
- (void)willStartLocatingUser{ 
NSLog(@"start locate");
}
/** *用戶方向更新后,會(huì)調(diào)用此函數(shù) *@param userLocation 新的用戶位置 */
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation{ 
  NSLog(@"heading is %@",userLocation.heading);
}
/** *用戶位置更新后,會(huì)調(diào)用此函數(shù) *@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; 
//發(fā)送反編碼請(qǐng)求.并返回是否成功 
BOOL flag = [_geoCodeSearch reverseGeoCode:reverseGeoCodeOption]; 
if (flag) { 
NSLog(@"反geo檢索發(fā)送成功");
 } else { 
NSLog(@"反geo檢索發(fā)送失敗");
 } // 停止定位 
[_locService stopUserLocationService];
}
/** *在地圖View停止定位后,會(huì)調(diào)用此函數(shù) *@param mapView 地圖View */
- (void)didStopLocatingUser{ 
NSLog(@"stop locate");
}
/** *定位失敗后,會(huì)調(diào)用此函數(shù) *@param mapView 地圖View *@param error 錯(cuò)誤號(hào),參考CLError.h中定義的錯(cuò)誤號(hào) */
- (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); 

// 定位城市后本地偏好設(shè)置存儲(chǔ)當(dāng)前城市編碼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.打開地圖界面 規(guī)劃路線
相關(guān)代碼如下:

import <UIKit/UIKit.h>

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

@end```

#import "QTXPlanningRouteMapController.h"
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Search/BMKSearchComponent.h>
#import <BaiduMapAPI_Utils/BMKUtilsComponent.h>
#import "QTXRouteAnnotation.h"
@interface QTXPlanningRouteMapController () <BMKMapViewDelegate, BMKRouteSearchDelegate> 
{ 
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; // 此處記得不用的時(shí)候需要置nil,否則影響內(nèi)存的釋放 
_routesearch.delegate = self; // 此處記得不用的時(shí)候需要置nil,否則影響內(nèi)存的釋放 
// 開始定位 
[self mapLocationClick];
}
-(void)viewWillDisappear:(BOOL)animated {
 [super viewWillDisappear:animated];
 _mapView.delegate = nil; // 不用時(shí),置nil 
_routesearch.delegate = nil; // 不用時(shí),置nil 
// 停止定位
// [_locService stopUserLocationService]; 
_mapView.showsUserLocation = NO;
}
- (void)dealloc {
 if (_routesearch != nil) {
 _routesearch = nil; 
}
 if (_mapView) { 
_mapView = nil; 
}
}
- (void)mapLocationClick { 
// 創(chuàng)建一張百度地圖 
// 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;//先關(guān)閉顯示的定位圖層 _mapView.userTrackingMode = BMKUserTrackingModeNone;//設(shè)置定位的狀態(tài) _mapView.showsUserLocation = YES;//顯示定位圖層 _mapView.showsUserLocation = YES; //顯示定位圖層(即我的位置的小圓點(diǎn)) [_mapView setZoomLevel:14]; //地圖顯示比例 
// [_mapView setMapType:BMKMapTypeStandard];
//設(shè)置地圖為標(biāo)準(zhǔn)類型
 // _mapView.rotateEnabled = NO; 
//設(shè)置是否可以旋轉(zhuǎn)
// [self onGeoSearch];
}
#pragma mark - BMKMapViewDelegate
- (BMKAnnotationView *)mapView:(BMKMapView *)view viewForAnnotation:(id <BMKAnnotation>)annotation{
 if ([annotation isKindOfClass:[QTXRouteAnnotation class]]) {
 return [self getQTXRouteAnnotationView:view viewForAnnotation:(QTXRouteAnnotation*)annotation]; 
}
 return nil;
}
- (BMKOverlayView*)mapView:(BMKMapView *)map viewForOverlay:(id<BMKOverlay>)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];
 // 計(jì)算路線方案中的路段數(shù)目 
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 = @"起點(diǎn)"; item.type = 0; 
[_mapView addAnnotation:item];
 // 添加起點(diǎn)標(biāo)注 
}else if(i==size-1){ 
QTXRouteAnnotation* item = [[QTXRouteAnnotation alloc]init];
 item.coordinate = plan.terminal.location; item.title = @"終點(diǎn)"; 
item.type = 1;
 [_mapView addAnnotation:item]; 
// 添加起點(diǎn)標(biāo)注 
} 
QTXRouteAnnotation* item = [[QTXRouteAnnotation alloc]init]; item.coordinate = transitStep.entrace.location;
 item.title = transitStep.instruction; item.type = 3;
 [_mapView addAnnotation:item]; 
//軌跡點(diǎn)總數(shù)累計(jì) 
planPointCounts += transitStep.pointsCount;
 }
 //軌跡點(diǎn) 
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<transitStep.pointsCount;k++) { 
temppoints[i].x = transitStep.points[k].x; 
temppoints[i].y = transitStep.points[k].y;
 i++;
 }
 }
 // 通過points構(gòu)建BMKPolyline BMKPolyline* polyLine = [BMKPolyline polylineWithPoints:temppoints count:planPointCounts]; 
[_mapView addOverlay:polyLine]; 
// 添加路線overlay 
delete []temppoints;
 [self mapViewFitPolyLine:polyLine];
 } else {
 [MBProgressHUD showError:@"位置暫時(shí)不確定,無(wú)法進(jìn)行規(guī)劃路線"];
 }
}
- (void)onGetDrivingRouteResult:(BMKRouteSearch*)searcher result:(BMKDrivingRouteResult*)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) { 
BMKDrivingRouteLine* plan = (BMKDrivingRouteLine*)[result.routes objectAtIndex:0]; 
// 計(jì)算路線方案中的路段數(shù)目 
NSInteger size = [plan.steps count];
 int planPointCounts = 0; 
for (int i = 0; i < size; i++) { 
BMKDrivingStep* transitStep = [plan.steps objectAtIndex:i]; 
if(i==0){ 
QTXRouteAnnotation* item = [[QTXRouteAnnotation alloc]init]; 
item.coordinate = plan.starting.location; 
item.title = @"起點(diǎn)";
 item.type = 0;
 [_mapView addAnnotation:item]; 
// 添加起點(diǎn)標(biāo)注
 }else if(i==size-1){ 
QTXRouteAnnotation* item = [[QTXRouteAnnotation alloc]init];
 item.coordinate = plan.terminal.location; 
item.title = @"終點(diǎn)";
 item.type = 1; 
[_mapView addAnnotation:item]; 
// 添加起點(diǎn)標(biāo)注
 }
 //添加annotation節(jié)點(diǎn) 
QTXRouteAnnotation* item = [[QTXRouteAnnotation alloc]init]; 
item.coordinate = transitStep.entrace.location; item.title = transitStep.entraceInstruction;
 item.degree = transitStep.direction * 30; item.type = 4; 
[_mapView addAnnotation:item]; 
//軌跡點(diǎn)總數(shù)累計(jì) 
planPointCounts += transitStep.pointsCount;
 }
 // 添加途經(jīng)點(diǎn) 
if (plan.wayPoints) { 
for (BMKPlanNode* tempNode in plan.wayPoints) { 
QTXRouteAnnotation* item = [[QTXRouteAnnotation alloc]init]; 
item = [[QTXRouteAnnotation alloc]init]; item.coordinate = tempNode.pt; item.type = 5; item.title = tempNode.name; 
[_mapView addAnnotation:item];
 }
 }
 //軌跡點(diǎn) 
BMKMapPoint * temppoints = new BMKMapPoint[planPointCounts]; 
int i = 0;
 for (int j = 0; j < size; j++) { 
BMKDrivingStep* transitStep = [plan.steps objectAtIndex:j]; 
int k=0;
 for(k=0;k<transitStep.pointsCount;k++) { 
temppoints[i].x = transitStep.points[k].x; temppoints[i].y = transitStep.points[k].y; 
i++; 
}
 } 
// 通過points構(gòu)建BMKPolyline 
BMKPolyline* polyLine = [BMKPolyline polylineWithPoints:temppoints count:planPointCounts]; 
[_mapView addOverlay:polyLine]; 
// 添加路線overlay 
delete []temppoints; 
[self mapViewFitPolyLine:polyLine]; 
} else {
 [MBProgressHUD showError:@"位置暫時(shí)不確定,無(wú)法進(jìn)行規(guī)劃路線"]; 
}
}
- (void)onGetWalkingRouteResult:(BMKRouteSearch*)searcher result:(BMKWalkingRouteResult*)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) { 
BMKWalkingRouteLine* plan = (BMKWalkingRouteLine*)[result.routes objectAtIndex:0]; 
NSInteger size = [plan.steps count];
 int planPointCounts = 0; 
for (int i = 0; i < size; i++) { 
BMKWalkingStep* transitStep = [plan.steps objectAtIndex:i]; 
if(i == 0){ 
QTXRouteAnnotation* item = [[QTXRouteAnnotation alloc]init];
 item.coordinate = plan.starting.location;
 item.title = @"起點(diǎn)";
 item.type = 0;
 [_mapView addAnnotation:item];
 // 添加起點(diǎn)標(biāo)注 
}else if(i==size-1){
 QTXRouteAnnotation* item = [[QTXRouteAnnotation alloc]init]; 
item.coordinate = plan.terminal.location;
 item.title = @"終點(diǎn)";
 item.type = 1; 
[_mapView addAnnotation:item]; // 添加起點(diǎn)標(biāo)注 
} //添加annotation節(jié)點(diǎn) 
QTXRouteAnnotation* item = [[QTXRouteAnnotation alloc]init]; 
item.coordinate = transitStep.entrace.location; 
item.title = transitStep.entraceInstruction; 
item.degree = transitStep.direction * 30; 
item.type = 4; 
[_mapView addAnnotation:item];
 //軌跡點(diǎn)總數(shù)累計(jì) planPointCounts += transitStep.pointsCount; 
} 
//軌跡點(diǎn) 
BMKMapPoint * temppoints = new BMKMapPoint[planPointCounts]; 
int i = 0; 
for (int j = 0; j < size; j++) { 
BMKWalkingStep* transitStep = [plan.steps objectAtIndex:j]; 
int k=0; 
for(k=0;k<transitStep.pointsCount;k++) { 
temppoints[i].x = transitStep.points[k].x; 
temppoints[i].y = transitStep.points[k].y; 
i++; 
}
 }
 // 通過points構(gòu)建BMKPolyline 
BMKPolyline* polyLine = [BMKPolyline polylineWithPoints:temppoints count:planPointCounts];
 [_mapView addOverlay:polyLine]; 
// 添加路線overlay 
delete []temppoints;
 [self mapViewFitPolyLine:polyLine]; 
} else {
 [MBProgressHUD showError:@"位置暫時(shí)不確定,無(wú)法進(jìn)行規(guī)劃路線"]; 
}
}
//根據(jù)polyline設(shè)置地圖范圍
- (void)mapViewFitPolyLine:(BMKPolyline *) polyLine { 
CGFloat ltX, ltY, rbX, rbY;
 if (polyLine.pointCount < 1) { 
return;
 }
 BMKMapPoint pt = polyLine.points[0];
 ltX = pt.x, ltY = pt.y;
 rbX = pt.x, rbY = pt.y; 
for (int i = 1; i < polyLine.pointCount; i++) { 
BMKMapPoint pt = polyLine.points[i]; 
if (pt.x < ltX) { ltX = pt.x; }
 if (pt.x > 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 - 百度地圖 大頭針圖像擴(kuò)展(旋轉(zhuǎn)效果)
- (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

// 步行路線規(guī)劃
-(void)onClickWalkSearch {
 // 起始地址
 BMKPlanNode *start = [[BMKPlanNode alloc]init]; 
start.name = [[NSUserDefaults standardUserDefaults] objectForKey:@"street"]; 
start.cityName = [[NSUserDefaults standardUserDefaults] objectForKey:@"city"]; 
//
 結(jié)束地址 
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檢索發(fā)送成功"); 
} else { 
NSLog(@"walk檢索發(fā)送失敗");
 }
}
// 公交路線規(guī)劃
-(void)onClickBusSearch { 
// 起始地址 
BMKPlanNode *start = [[BMKPlanNode alloc]init]; 
start.name = [[NSUserDefaults standardUserDefaults] objectForKey:@"street"]; 
start.cityName = [[NSUserDefaults standardUserDefaults] objectForKey:@"city"]; 
// 結(jié)束地址 
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檢索發(fā)送成功"); 
} else { 
NSLog(@"bus檢索發(fā)送失敗");
 }
}
// 駕車路線規(guī)劃
-(void)onClickCarSearch {
 // 起始地址 
BMKPlanNode *start = [[BMKPlanNode alloc]init]; 
start.name = [[NSUserDefaults standardUserDefaults] objectForKey:@"street"]; 
start.cityName = [[NSUserDefaults standardUserDefaults] objectForKey:@"city"];
 // 結(jié)束地址 
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檢索發(fā)送成功"); 
} else { 
NSLog(@"car檢索發(fā)送失敗"); 
}
}```
![](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.打開地圖界面 大頭針定位
相關(guān)代碼如下:

import <UIKit/UIKit.h>

@interface QTXOpenMapController : UIViewController <BMKMapViewDelegate, BMKLocationServiceDelegate> {
BMKMapManager *_mapManager;
BMKLocationService *_locService;
BMKMapView *_mapView;
}
@end```

#import "QTXOpenMapController.h"
@interface QTXOpenMapController () <BMKGeoCodeSearchDelegate> { 
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; // 此處記得不用的時(shí)候需要置nil,否則影響內(nèi)存的釋放 
// 開始定位
 [self mapLocationClick];
}
- (void)backClick { 
// 停止定位 
[_locService stopUserLocationService];
 _mapView.showsUserLocation = NO; 
[self.navigationController popViewControllerAnimated:YES];
}
- (void)mapLocationClick { 
// 創(chuàng)建一張百度地圖
 // 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;//先關(guān)閉顯示的定位圖層 
_mapView.userTrackingMode = BMKUserTrackingModeNone;//設(shè)置定位的狀態(tài) 
_mapView.showsUserLocation = YES;//顯示定位圖層 
_mapView.showsUserLocation = YES; //顯示定位圖層(即我的位置的小圓點(diǎn)) 
[_mapView setZoomLevel:14]; //地圖顯示比例 
[self onGeoSearch];
}
-(void)viewWillAppear:(BOOL)animated {
 [_mapView viewWillAppear];
 _mapView.delegate = self; // 此處記得不用的時(shí)候需要置nil,否則影響內(nèi)存的釋放 
_locService.delegate = self; // 大頭針 
BMKPointAnnotation *annotation = [[BMKPointAnnotation alloc] init];
 [_mapView addAnnotation:annotation]; 
self.annotation = annotation;
}
-(void)viewWillDisappear:(BOOL)animated {
 [_mapView viewWillDisappear];
 _mapView.delegate = nil; // 不用時(shí),置nil 
_locService.delegate = nil;
}
/** *在地圖View將要啟動(dòng)定位時(shí),會(huì)調(diào)用此函數(shù) *@param mapView 地圖View */
- (void)willStartLocatingUser{ 
NSLog(@"start locate");
}
/** *用戶方向更新后,會(huì)調(diào)用此函數(shù) *@param userLocation 新的用戶位置 */
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation{ 
[_mapView updateLocationData:userLocation]; 
NSLog(@"heading is %@",userLocation.heading);
}
/** *用戶位置更新后,會(huì)調(diào)用此函數(shù) *@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停止定位后,會(huì)調(diào)用此函數(shù) *@param mapView 地圖View */
- (void)didStopLocatingUser{ 
NSLog(@"stop locate");
}
/** *定位失敗后,會(huì)調(diào)用此函數(shù) *
@param mapView 地圖View *
@param error 錯(cuò)誤號(hào),參考CLError.h中定義的錯(cuò)誤號(hào) */
- (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 -傳入定位坐標(biāo)// 設(shè)置定位到得用戶的位置,這里是簡(jiǎn)單的應(yīng)用方法(必須打開程序時(shí)已經(jīng)獲取到地理位置坐標(biāo),為了解決地圖定位時(shí)總是先顯示天安門)
- (void)passLocationValue:(BMKUserLocation *)userLocation{ 
_mapView.centerCoordinate = userLocation.location.coordinate;
}
// 根據(jù)anntation生成對(duì)應(yīng)的View
- (BMKAnnotationView *)mapView:(BMKMapView *)view viewForAnnotation:(id <BMKAnnotation>)annotation{ 
NSString *AnnotationViewID = @"annotationViewID"; 
//根據(jù)指定標(biāo)識(shí)查找一個(gè)可被復(fù)用的標(biāo)注View,一般在delegate中使用,用此函數(shù)來代替新申請(qǐng)一個(gè)View 
BMKAnnotationView *annotationView = [view dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID]; 
if (annotationView == nil) { 
annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID]; 
((BMKPinAnnotationView*)annotationView).pinColor = BMKPinAnnotationColorRed; 
((BMKPinAnnotationView*)annotationView).animatesDrop = YES; // 設(shè)置該標(biāo)注點(diǎn)動(dòng)畫顯示 
} 
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檢索發(fā)送成功");
 } else { 
NSLog(@"geo檢索發(fā)送失敗");
 }}
- (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:@"暫無(wú)詳細(xì)地址"]; 
}
}
- (void)didReceiveMemoryWarning { 
[super didReceiveMemoryWarning]; 
// Dispose of any resources that can be recreated.
}
@end```
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容