Developers can download the iOS SDK download page on baidu map to the latest version of the map SDK, download address is: http://developer.baidu.com/map/index.php?title=iossdk/sdkiosdev-download

# # 1. The application key baidu map iOS SDK development key application address is: http://lbsyun.baidu.com/apiconsole/key

##2. Configure the development environment

Baidu Map iOS SDK provides the. Framework package in the form of subcontracting. Please ensure that the subcontracting versions are consistent when you use it. BaiduMapAPI_Base. Framework is the base package. Any function of SDK needs to be imported, and other subpackages can be imported as required. Copy the desired BaiduMapAPI_. Framework to the project folder. Click the “+” button in the TARGETS->Build Phases-> Link Binary With Libaries, click the “Add Other” button in the popup window and select BaiduMapAPI_. Framework to Add to the project. Note: The static library is implemented in Objective-C++, so you need to ensure that your project has at least one source file with a **. Mm ** suffix (you can rename any.m file to.mm), or specify the compilation method in the project properties. Compile Sources As in Xcode’s Project -> Edit Active Target -> Build Setting Baidu map SDK provides positioning functions and animation effects, v2.0.0 version began to use OpenGL rendering, So you need to CoreLocation introduction in your Xcode project. The framework and QuartzCore framework, OpenGLES. Framework, SystemConfiguration framework, CoreGraph Ics. framework, security. framework, libsqlite3.0.tbd (xcode7 was libsqlite3.0.dylib), CoreTelephony. Framework , libstdc++.6.0.9. TBD (xcode7 was libstdc++.6.0.9.dylib). (Note: The system libraries marked in bold are the new system libraries added in V2.9.0. If you use the map SDK of V2.9.0 or later, you must import these three system libraries.) Xcode: Project -> Active Target ->Build Phases ->Link Binary With Libraries

Mapapi. Bundle contains resource images for location, default pin views, and route points, as well as resource files necessary for vector map drawing. If you do not need to use the built-in image display capability, you can remove the image folder in the bundle. You can also replace or delete the image files in the image folder in the bundle as required. ** Method: ** Select the project name, right-click the menu and choose Add Files to “Project name”… , from BaiduMapAPI_Map framework | | Resources file selection mapapi. The bundle file, then select “Copy items if men” check box, click the “Add” button to Add a resource file to the project.

1) If you only use BMKMapView in Xib file, and do not use BMKMapView in code, the compiler will not link the corresponding symbol, you need to explicitly set the project properties: Add ** -objc ** in Xcode’s Project -> Edit Active Target -> Build Setting -> Other Linker Flags

2) Because iOS9 uses more secure HTTPS, in order to use map SDK normally in iOS9, please do the following configuration in “info.plist”, otherwise the use of SDK will be affected.

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>
Copy the code

3) if you use the function of enabling baidu map client in iOS9, you must perform the following configuration in “info.plist”; otherwise, baidu map client cannot be enabled.

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>baidumap</string>
</array>
Copy the code

###2.5 import header files

Classes that use the SDK introduce the following header files as needed:#import 
 
#import 
      
       // import all header files for map functionality
      
 
# import < BaiduMapAPI_Search/BMKSearchComponent. H > / / introduced retrieval functions all the header files
 
# import < BaiduMapAPI_Cloud/BMKCloudSearchComponent. H > / / into cloud retrieval functions all the header files
 
# import < BaiduMapAPI_Location/BMKLocationComponent. H > / / introduce positioning function all the header files
 
# import < BaiduMapAPI_Utils/BMKUtilsComponent. H > / / introduce computational tools all the header files
 
# import < BaiduMapAPI_Radar/BMKRadarComponent. H > / / introduction surrounding radar function all the header files
 
#import < BaiduMapAPI_Map/ bmkmapView.h >// import only the single header file required
Copy the code

##3. Relevant codes

Since 2.0.0, BMKMapView has added viewWillAppear, viewWillDisappear methods to control BMKMapView’s life cycle. Only one BMKMapView can receive a callback message at a time. Therefore, the viewController using BMKMapView needs to call the corresponding method of BMKMapView in viewWillAppear and viewWillDisappear, and process the delegate. The code is as follows:

-(void)viewWillAppear:(BOOL)animated { [_mapView viewWillAppear]; _mapView.delegate = self; } -(void)viewWillDisappear:(BOOL)animated {[_mapView viewWillDisappear]; _mapView.delegate = nil; // set nil}Copy the code

Start BaiduMapManager from BaidumapDelegate.

@interface AppDelegate : NSObject <UIApplicationDelegate, BMKGeneralDelegate>
{
    BMKMapManager* _mapManager;
}
Copy the code
@implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary  *)launchOptions { // 1. Create window self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; // 2. Set the window root controller [self.window switchRootViewController]; Display window [self.window makeKeyAndVisible];float version = [[[UIDevice currentDevice] systemVersion] floatValue];
    if(version > = 8.0) {/ / iOS8 + IconBadge need authorization UIUserNotificationSettings * Settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge categories:nil]; [[UIApplication sharedApplication] registerUserNotificationSettings:settings]; } // BaiduMapManager _mapManager = [[BMKMapManager alloc]init]; // Set the generalDelegate parameter BOOL ret = [_mapManager start:BaiduMapAppKey generalDelegate:self];if(! ret) { NSLog(@"manager start failed!");
    }

    return YES;
}
Copy the code

1) Since iOS SDK V2.5.0, in order to make compatible with iOS8 positioning ability, we have made corresponding modifications, developers in the use of the process of attention to the following:

Need info. Add in the plist (the following a choice, both add default NSLocationWhenInUseUsageDescription) : NSLocationWhenInUseUsageDescription, allowing the description at the front desk to get when using GPS NSLocationAlwaysUsageDescription, allowing permanent described using GPSCopy the code

2) Part of the code is as follows:

@interface QTXHomeController ()<BMKLocationServiceDelegate, BMKGeoCodeSearchDelegate> { BMKLocationService *_locService;  BMKGeoCodeSearch *_geoCodeSearch; }Copy the code
- (void)viewDidLoad { [super viewDidLoad]; // Set map location [self setupBMKLocation]; }#pragma mark - BMKLocationService- (void)setupBMKLocation {// Initialize BMKLocationService _locService = [[BMKLocationService alloc]init]; _locService.delegate = self; _geoCodeSearch = [[BMKGeoCodeSearch alloc] init]; _geoCodeSearch.delegate = self; // Start 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 implement relevant delegate processing position information update@param mapView mapView */ - (void)willStartLocatingUser {NSLog(@)"start locate"); } /** * After the user direction is updated, *@param userLocation new userLocation */ - (void)didUpdateUserHeading (BMKUserLocation *)userLocation {NSLog(@)"heading is %@",userLocation.heading); } /** * After the user location is updated, Will call this function * @ param userLocation new user location * / - (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; // Send the unencoding request. And return the success of a Boolean flag = [_geoCodeSearch reverseGeoCode: reverseGeoCodeOption];if (flag) {
        NSLog(@"Reverse GEO search sent successfully");
    } else {
        NSLog(@"Reverse GEO search send failed"); } // stop location [_locService stopUserLocationService]; } @param mapView mapView */ - (void)didStopLocatingUser {NSLog(@)"stop locate"); } @param mapView mapView @param error error number, Error number defined in reference CLError. H * / - (void) didFailToLocateUserWithError (NSError *) error {NSLog (@"location error");
    NSString *city = [[NSUserDefaults standardUserDefaults] objectForKey:@"cityNmae"];
    [self.cityBtn setTitle:city forState:UIControlStateNormal]; } / / reverse geocoding - (void) onGetReverseGeoCodeResult: (BMKGeoCodeSearch *) a 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); [[NSUserDefaults standardUserDefaults]] [NSUserDefaults standardUserDefaults]setObject:self.cityCode forKey:@"cityCode"]; [[NSUserDefaults standardUserDefaults] synchronize]; // City [[NSUserDefaults standardUserDefaults]setObject:[result.poiList.firstObject city] forKey:@"city"]; [[NSUserDefaults standardUserDefaults] synchronize]; // Save the street address [[NSUserDefaults standardUserDefaults]setObject:result.addressDetail.streetName forKey:@"street"]; [[NSUserDefaults standardUserDefaults] synchronize]; }}Copy the code

##5. Open the map interface and plan the route related codes as follows:

#import <UIKit/UIKit.h>

@interface QTXPlanningRouteMapController : UIViewController
{
    BMKRouteSearch * _routesearch;
}

@property (nonatomic, copy) NSString *address;

@end
Copy the code
#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; _routesearch.delegate = self; // start position [self mapLocationClick]; // start position [self mapLocationClick]; } -(void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; _mapView.delegate = nil; // set nil _routesearch.delegate = nil; // [_locService stopUserLocationService]; _mapView.showsUserLocation = NO; } - (void)dealloc {if(_routesearch ! = nil) { _routesearch = nil; }if(_mapView) { _mapView = nil; }} - (void)mapLocationClick {// create a map // 1. _mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 0, UI_View_Width, UI_View_Height)]; _mapView.delegate = self; [self.view addSubview:_mapView]; // _locService = [[BMKLocationService alloc]init]; // [_locService startUserLocationService]; _mapView.showsUserLocation = NO; UserTrackingMode = BMKUserTrackingModeNone; / / set the orientation of state _mapView. ShowsUserLocation = YES; / / show the positioning layer _mapView showsUserLocation = YES; // Displays the positioning layer (the little dot in my position) [_mapViewsetZoomLevel:14]; // map display scale // [_mapViewsetMapType:BMKMapTypeStandard]; // set the map type to standard // _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]; StrokeColor = [[UIColor alloc] initWithRed:0 green:0 blue:1 alpha:0.7]; polylineView.strokeColor = [UIColor alloc] initWithRed:0 green:0 blue:1 alpha:0.7]; PolylineView. Our 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 = @"Starting point"; item.type = 0; [_mapView addAnnotation:item]; // add the starting point}else if(i==size-1){
                QTXRouteAnnotation* item = [[QTXRouteAnnotation alloc]init];
                item.coordinate = plan.terminal.location;
                item.title = @"The end"; 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++; }} / / by points to construct BMKPolyline BMKPolyline * polyLine = [BMKPolyline polylineWithPoints: temppoints count: planPointCounts]; [_mapView addOverlay:polyLine]; // add route overlay delete []temppoints; [self mapViewFitPolyLine:polyLine]; }else {
        [MBProgressHUD showError:@"The location is temporarily uncertain, and the route cannot be planned."];
    }
}
- (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 = @"Starting point"; item.type = 0; [_mapView addAnnotation:item]; // add the starting point}else if(i==size-1){
                QTXRouteAnnotation* item = [[QTXRouteAnnotation alloc]init];
                item.coordinate = plan.terminal.location;
                item.title = @"The end"; item.type = 1; [_mapView addAnnotation:item]; 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; } // Add passing pointsif (plan.wayPoints) {
            for (BMKPlanNode* tempNode inplan.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++; }} / / by points to construct BMKPolyline BMKPolyline * polyLine = [BMKPolyline polylineWithPoints: temppoints count: planPointCounts]; [_mapView addOverlay:polyLine]; // add route overlay delete []temppoints; [self mapViewFitPolyLine:polyLine]; }else {
        [MBProgressHUD showError:@"The location is temporarily uncertain, and the route cannot be planned."];
    }
}

- (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 = @"Starting point"; item.type = 0; [_mapView addAnnotation:item]; // add the starting point}else if(i==size-1){
                QTXRouteAnnotation* item = [[QTXRouteAnnotation alloc]init];
                item.coordinate = plan.terminal.location;
                item.title = @"The end"; item.type = 1; [_mapView addAnnotation:item]; 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++; }} / / by points to construct BMKPolyline BMKPolyline * polyLine = [BMKPolyline polylineWithPoints: temppoints count: planPointCounts]; [_mapView addOverlay:polyLine]; // add route overlay delete []temppoints; [self mapViewFitPolyLine:polyLine]; }else {
        [MBProgressHUD showError:@"The location is temporarily uncertain, and the route cannot be planned."]; }} // set the map scope according to 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 - Baidu Map pin image extension (rotation effect)
- (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
Copy the code
-(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 retrieval sent successfully");
    } else {
        NSLog(@"Walk retrieve send failed"); }} // public transit route planning -(void)onClickBusSearch {// start address 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 retrieval sent successfully");
    } else {
        NSLog(@"Bus retrieval send failed"); }} -(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 retrieval sent successfully");
    } else {
        NSLog(@"Car retrieval send failed"); }}Copy the code

##6. Pin location codes are as follows:

#import <UIKit/UIKit.h>

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

@end

Copy the code
#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; // start position [self mapLocationClick]; // start position [self mapLocationClick]; } - (void)backClick {// stop location [_locService stopUserLocationService]; _mapView.showsUserLocation = NO; [self.navigationController popViewControllerAnimated:YES]; } - (void)mapLocationClick {// create a map // 1. _mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 0, UI_View_Width, UI_View_Height)]; _mapView.delegate = self; [self.view addSubview:_mapView]; _locService = [[BMKLocationService alloc]init]; [_locService startUserLocationService]; _mapView.showsUserLocation = NO; UserTrackingMode = BMKUserTrackingModeNone; / / set the orientation of state _mapView. ShowsUserLocation = YES; / / show the positioning layer _mapView showsUserLocation = YES; // Displays the positioning layer (the little dot in my position) [_mapViewsetZoomLevel:14]; // Map display scale [self onGeoSearch]; } -(void)viewWillAppear:(BOOL)animated { [_mapView viewWillAppear]; _mapView.delegate = self; _locservice.delegate = self; _locservice.delegate = self; // BMKPointAnnotation *annotation = [[BMKPointAnnotation alloc] init]; [_mapView addAnnotation:annotation]; self.annotation = annotation; } -(void)viewWillDisappear:(BOOL)animated { [_mapView viewWillDisappear]; _mapView.delegate = nil; _locservice. delegate = nil; } @param mapView mapView */ - (void)willStartLocatingUser {NSLog(@)"start locate"); } /** * After the user direction is updated, *@param userLocation new userLocation */ - (void)didUpdateUserHeading (BMKUserLocation *)userLocation {[_mapView updateLocationData:userLocation]; NSLog(@"heading is %@",userLocation.heading); } /** * After the user location is updated, Will call this function * @ param userLocation new user location * / - (void) didUpdateBMKUserLocation (BMKUserLocation *) userLocation {NSLog (@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude); self.userLocation = userLocation; [_mapView updateLocationData:userLocation]; } @param mapView mapView */ - (void)didStopLocatingUser {NSLog(@)"stop locate"); } @param mapView mapView @param error error number, Error number defined in reference 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:@"Map initialization completed" delegate:nil cancelButtonTitle:@"Got it."otherButtonTitles: nil]; // [alert show]; // alert = nil; // // start geocoding // [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 - Passes in positioning coordinates// Set the location to the user's location, here is a simple application method (must open the program has obtained the geographic location coordinates, - (void)passLocationValue:(BMKUserLocation *)userLocation {_mapview.centercoordinate = userLocation.location.coordinate; } // Generate corresponding View - (BMKAnnotationView *)mapView (BMKMapView *) View viewForAnnotation (ID) according to anntation <BMKAnnotation>)annotation { NSString *AnnotationViewID = @"annotationViewID"; // Find a View that can be reused based on the specified identity. BMKAnnotationView *annotationView = [View dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];if (annotationView == nil) {
        annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
        ((BMKPinAnnotationView*)annotationView).pinColor = BMKPinAnnotationColorRed;
        ((BMKPinAnnotationView*)annotationView).animatesDrop = YES; / / set the mark point animation shows.} annotationView centerOffset = CGPointMake (0, - (annotationView. Frame. The 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 retrieval sent successfully");
    } else {
        NSLog(@"Failed to send geo retrieval");
    }
}

- (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:@"No detailed address at present"];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
Copy the code