開發(fā)者可在百度地圖iOS SDK的下載頁面下載到最新版的地圖SDK奋构,下載地址為:http://developer.baidu.com/map/index.php?title=iossdk/sdkiosdev-download
1.申請密鑰
百度地圖iOS SDK開發(fā)密鑰的申請地址為:
http://lbsyun.baidu.com/apiconsole/key
2.配置開發(fā)環(huán)境
2.1、根據(jù)需要導(dǎo)入 .framework包
百度地圖 iOS SDK 采用分包的形式提供 .framework包宪摧,請廣大開發(fā)者使用時確保各分包的版本保持一致虱岂。其中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)庫中采用Objective-C++實現(xiàn),因此需要您保證您工程中至少有一個**.mm**后綴的源文件(您可以將任意一個.m后綴的文件改名為.mm)巢块,或者在工程屬性中指定編譯方式礁阁,即在Xcode的Project -> Edit Active Target -> Build Setting 中找到 Compile Sources As,并將其設(shè)置為**"Objective-C++"**
2.2夕冲、引入所需的系統(tǒng)庫
百度地圖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)疼进。
(注:加粗標(biāo)識的系統(tǒng)庫為v2.9.0新增的系統(tǒng)庫薪缆,使用v2.9.0及以上版本的地圖SDK,務(wù)必增加導(dǎo)入這3個系統(tǒng)庫伞广。)
添加方式:在Xcode的Project -> Active Target ->Build Phases ->Link Binary With Libraries拣帽,添加這幾個系統(tǒng)庫即可。
2.3嚼锄、引入mapapi.bundle資源文件
如果使用了基礎(chǔ)地圖功能减拭,需要添加該資源,否則地圖不能正常顯示mapapi.bundle中存儲了定位区丑、默認(rèn)大頭針標(biāo)注View及路線關(guān)鍵點(diǎn)的資源圖片拧粪,還存儲了矢量地圖繪制必需的資源文件。如果您不需要使用內(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,編譯器在鏈接時不會鏈接對應(yīng)符號罩驻,需要在工程屬性中顯式設(shè)定:在Xcode的Project -> Edit Active Target -> Build Setting -> Other Linker Flags中添加-ObjC
2)由于iOS9改用更安全的https穗酥,為了能夠在iOS9中正常使用地圖SDK,請在"Info.plist"中進(jìn)行如下配置惠遏,否則影響SDK的使用砾跃。
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
3)如果在iOS9中使用了調(diào)起百度地圖客戶端功能,必須在"Info.plist"中進(jìn)行如下配置节吮,否則不能調(diào)起百度地圖客戶端抽高。
<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>//引入計算工具所有的頭文件
#import <BaiduMapAPI_Radar/BMKRadarComponent.h>//引入周邊雷達(dá)功能所有的頭文件
#import < BaiduMapAPI_Map/BMKMapView.h>//只引入所需的單個頭文件
3透绩、相關(guān)代碼
3.1管理地圖的生命周期
自2.0.0起翘骂,BMKMapView新增viewWillAppear壁熄、viewWillDisappear方法來控制BMKMapView的生命周期,并且在一個時刻只能有一個BMKMapView接受回調(diào)消息碳竟,因此在使用BMKMapView的viewController中需要在viewWillAppear草丧、viewWillDisappear方法中調(diào)用BMKMapView的對應(yīng)的方法,并處理delegate莹桅,代碼如下:
-(void)viewWillAppear:(BOOL)animated
{
[_mapView viewWillAppear];
_mapView.delegate = self; // 此處記得不用的時候需要置nil昌执,否則影響內(nèi)存的釋放
}
-(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.創(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];
}
// 要使用百度地圖懂拾,請先啟動BaiduMapManager
_mapManager = [[BMKMapManager alloc]init];
// 如果要關(guān)注網(wǎng)絡(luò)及授權(quán)驗證事件麦备,請設(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起,為了對iOS8的定位能力做兼容蓄愁,做了相應(yīng)的修改娶桦,開發(fā)者在使用過程中注意事項如下:
需要在info.plist里添加(以下二選一,兩個都添加默認(rèn)使用NSLocationWhenInUseUsageDescription):
NSLocationWhenInUseUsageDescription 汁汗,允許在前臺使用時獲取GPS的描述
NSLocationAlwaysUsageDescription 衷畦,允許永久使用GPS的描述
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;
//啟動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 實現(xiàn)相關(guān)delegate 處理位置信息更新
/**
*在地圖View將要啟動定位時,會調(diào)用此函數(shù)
*@param mapView 地圖View
*/
- (void)willStartLocatingUser
{
NSLog(@"start locate");
}
/**
*用戶方向更新后知牌,會調(diào)用此函數(shù)
*@param userLocation 新的用戶位置
*/
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
NSLog(@"heading is %@",userLocation.heading);
}
/**
*用戶位置更新后祈争,會調(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ā)送反編碼請求.并返回是否成功
BOOL flag = [_geoCodeSearch reverseGeoCode:reverseGeoCodeOption];
if (flag) {
NSLog(@"反geo檢索發(fā)送成功");
} else {
NSLog(@"反geo檢索發(fā)送失敗");
}
// 停止定位
[_locService stopUserLocationService];
}
/**
*在地圖View停止定位后,會調(diào)用此函數(shù)
*@param mapView 地圖View
*/
- (void)didStopLocatingUser
{
NSLog(@"stop locate");
}
/**
*定位失敗后角寸,會調(diào)用此函數(shù)
*@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);
// 定位城市后本地偏好設(shè)置存儲當(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; // 此處記得不用的時候需要置nil扁藕,否則影響內(nèi)存的釋放
_routesearch.delegate = self; // 此處記得不用的時候需要置nil沮峡,否則影響內(nèi)存的釋放
// 開始定位
[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 {
// 創(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];
// 計算路線方案中的路段數(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ù)累計
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:@"位置暫時不確定邢疙,無法進(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];
// 計算路線方案中的路段數(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ù)累計
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:@"位置暫時不確定,無法進(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ù)累計
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:@"位置暫時不確定望薄,無法進(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ā)送失敗");
}
}
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; // 此處記得不用的時候需要置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; // 此處記得不用的時候需要置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; // 不用時痕支,置nil
_locService.delegate = nil;
}
/**
*在地圖View將要啟動定位時颁虐,會調(diào)用此函數(shù)
*@param mapView 地圖View
*/
- (void)willStartLocatingUser
{
NSLog(@"start locate");
}
/**
*用戶方向更新后,會調(diào)用此函數(shù)
*@param userLocation 新的用戶位置
*/
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
[_mapView updateLocationData:userLocation];
NSLog(@"heading is %@",userLocation.heading);
}
/**
*用戶位置更新后卧须,會調(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停止定位后另绩,會調(diào)用此函數(shù)
*@param mapView 地圖View
*/
- (void)didStopLocatingUser
{
NSLog(@"stop locate");
}
/**
*定位失敗后儒陨,會調(diào)用此函數(shù)
*@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 -傳入定位坐標(biāo)
// 設(shè)置定位到得用戶的位置板熊,這里是簡單的應(yīng)用方法(必須打開程序時已經(jīng)獲取到地理位置坐標(biāo)框全,為了解決地圖定位時總是先顯示天安門)
- (void)passLocationValue:(BMKUserLocation *)userLocation
{
_mapView.centerCoordinate = userLocation.location.coordinate;
}
// 根據(jù)anntation生成對應(yīng)的View
- (BMKAnnotationView *)mapView:(BMKMapView *)view viewForAnnotation:(id <BMKAnnotation>)annotation
{
NSString *AnnotationViewID = @"annotationViewID";
//根據(jù)指定標(biāo)識查找一個可被復(fù)用的標(biāo)注View,一般在delegate中使用干签,用此函數(shù)來代替新申請一個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)動畫顯示
}
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:@"暫無詳細(xì)地址"];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end