開發者可在百度地圖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,添加這幾個系統庫即可。
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的使用。
<key>NSAppTransportSecurity</key><dict> <key>NSAllowsArbitraryLoads</key> <true/></dict>```
3)如果在iOS9中使用了調起百度地圖客戶端功能,必須在"Info.plist"中進行如下配置,否則不能調起百度地圖客戶端。

<key>LSApplicationQueriesSchemes</key><array> <string>baidumap</string></array>```
2.5、引入頭文件
在使用SDK的類 按需 引入下邊的頭文件:
#import <BaiduMapAPI_Base/BMKBaseComponent.h>//引入base相關所有的頭文件
#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>//引入計算工具所有的頭文件
#import <BaiduMapAPI_Radar/BMKRadarComponent.h>//引入周邊雷達功能所有的頭文件
#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 <UIApplicationDelegate, BMKGeneralDelegate>{ 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的描述```

2)部分代碼如下:
@interface QTXHomeController ()<BMKLocationServiceDelegate, BMKGeoCodeSearchDelegate>{
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 <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; // 此處記得不用的時候需要置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 <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];
// 計算路線方案中的路段數目
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<transitStep.pointsCount;k++) {
temppoints[i].x = transitStep.points[k].x;
temppoints[i].y = transitStep.points[k].y;
i++;
}
}
// 通過points構建BMKPolyline BMKPolyline* polyLine = [BMKPolyline polylineWithPoints:temppoints count:planPointCounts];
[_mapView addOverlay:polyLine];
// 添加路線overlay
delete []temppoints;
[self mapViewFitPolyLine:polyLine];
} else {
[MBProgressHUD showError:@"位置暫時不確定,無法進行規劃路線"];
}
}
- (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];
// 計算路線方案中的路段數目
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 = @"起點";
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];
// 添加起點標注
}
//添加annotation節點
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];
//軌跡點總數累計
planPointCounts += transitStep.pointsCount;
}
// 添加途經點
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];
}
}
//軌跡點
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構建BMKPolyline
BMKPolyline* polyLine = [BMKPolyline polylineWithPoints:temppoints count:planPointCounts];
[_mapView addOverlay:polyLine];
// 添加路線overlay
delete []temppoints;
[self mapViewFitPolyLine:polyLine];
} else {
[MBProgressHUD showError:@"位置暫時不確定,無法進行規劃路線"];
}
}
- (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 = @"起點";
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]; // 添加起點標注
} //添加annotation節點
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];
//軌跡點總數累計 planPointCounts += transitStep.pointsCount;
}
//軌跡點
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構建BMKPolyline
BMKPolyline* polyLine = [BMKPolyline polylineWithPoints:temppoints count:planPointCounts];
[_mapView addOverlay:polyLine];
// 添加路線overlay
delete []temppoints;
[self mapViewFitPolyLine:polyLine];
} else {
[MBProgressHUD showError:@"位置暫時不確定,無法進行規劃路線"];
}
}
//根據polyline設置地圖范圍
- (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 - 百度地圖 大頭針圖像擴展(旋轉效果)
- (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檢索發送失敗");
}
}```
駕車.png
公交.jpg
步行.jpg
#6.打開地圖界面 大頭針定位
相關代碼如下:
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; // 此處記得不用的時候需要置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 <BMKAnnotation>)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```