iOS Baidu Map-Path planning

Source: Internet
Author: User

The path planning function of Baidu map,
In the use of Baidu path, there are some small problems, in this, share your own simplest path small demo
Of course, the front of the Baidu configuration problem, I will not talk to you, because this is too much information! Now, let me introduce this little demo.

The APPDELEGATE.M file is as follows,

#import "AppDelegate.h"
Import "RootViewController.h"

@implementation Appdelegate

    • (BOOL) Application: (uiapplication ) application didfinishlaunchingwithoptions: (nsdictionary ) launchOptions
      {
      Self.window = [[UIWindow alloc] initwithframe:[[uiscreen mainscreen] bounds]];

      Self.window.backgroundColor = [Uicolor Whitecolor];

      Mapmanager = [[Bmkmapmanager alloc]init];
      If you want to focus on network and authorization validation events, set the Generaldelegate parameter
      BOOL ret = [
      mapmanager start:@ "6GP5E6XYGQN5ARRD1DK0VKCF" generaldelegate:nil];
      if (!ret) {

      NSLog (@ "manager start failed!");

      }

      Rootviewcontroller *ROOTVC = [[Rootviewcontroller alloc] init];
      Navigationcontroller = [[Uinavigationcontroller alloc] INITWITHROOTVIEWCONTROLLER:ROOTVC];
      Self.window.rootViewController =
      Navigationcontroller;

      [Self.window makekeyandvisible];
      return YES;

}

Then, ROOTVIEWCONTROLLER.M file as follows, here only walk this button has effect Oh!

#import "RootViewController.h"
Import "BMapKit.h"Define Mybundle_name @ "Mapapi.bundle"define Mybundle_path [[[NSBundle Mainbundle] ResourcePath] stringbyappendingpathcomponent:mybundle_name]Define Mybundle [NSBundle Bundlewithpath:mybundle_path]

@interface routeannotation:bmkpointannotation
{

int _type; <0: Starting point 1: End 2: Bus 3: Subway 4: Ride 5: via point int _degree;

}

@property (nonatomic) int type;
@property (nonatomic) int degree;
@end

@implementation Routeannotation

@synthesize type = type;
@synthesize degree =
degree;
@end

@interface Rootviewcontroller ()
{

Uitextfield *textfrom; Uitextfield *textto; UIButton *btnbus; UIButton *btncar; UIButton *btnfoot; UIView *_MAPV; bmkmapview* _mapview; bmkroutesearch* _routesearch;

}

@end

@implementation UIImage (Internalmethod)

    • (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

@interface Rootviewcontroller ()

@end

@implementation Rootviewcontroller

  • (NSString) getMyBundlePath1: (NSString ) FileName
    {

    NSBundle * Libbundle = Mybundle;
    if (libbundle && filename) {

    NSString * S=[[libbundle ResourcePath] Stringbyappendingpathcomponent:filename];return s;

    }
    return nil;
    }

  • (ID) Initwithnibname: (nsstring ) Nibnameornil Bundle: (NSBundle ) Nibbundleornil
    {
    self = [super Initwithnibname:nibnameornil Bundle:nibbundleornil];
    if (self) {

    Custom Initializationself.view.backgroundColor = [Uicolor Redcolor];

    }
    return self;
    }

  • (void) Viewdidload
    {
    [Super Viewdidload];
    Do any additional setup after loading the view.
    Self.title = @ "Path planning";

    [Self setupui];

    Textfrom.text = @ "Tiananmen Square";
    Textto.text = @ "Baidu building";

    Routesearch = [[Bmkroutesearch alloc]init];
    Routesearch.delegate = self;//Here Remember to need to set nil, otherwise affect the release of memory
    Mapview = [[Bmkmapview alloc]initwithframe:mapv.bounds];
    Mapview.delegate = self; Remember to set nil when not in use, otherwise affect the release of memory
    [
    MAPV Addsubview:_mapview];

}

-(void) setupui
{

UILabel *lablefrom = [[UILabel alloc] Initwithframe:cgrectmake (20,70, max.)];lablefrom.text = @ "starting point"; UILabel *lableto = [[UILabel alloc] Initwithframe:cgrectmake (20,120, max.)];lableto.text = @ "end point"; textfrom = [[Uitextfie] LD Alloc] Initwithframe:cgrectmake (+, A, a)];textfrom.backgroundcolor = [Uicolor Greencolor];textto = [[ Uitextfield Alloc] Initwithframe:cgrectmake (+)];textto.backgroundcolor = [Uicolor Greencolor];btnbus = [[ UIButton Alloc] Initwithframe:cgrectmake (20, 160, 40, 30)]; [Btnbus settitle:@ "bus" Forstate:uicontrolstatenormal];btncar = [[UIButton alloc] Initwithframe:cgrectmake (80, 160, 40, 30)]; [Btncar settitle:@ "drive" forstate:uicontrolstatenormal];btnfoot = [[UIButton alloc] Initwithframe:cgrectmake (150, 160, 40, 30)]; [Btnfoot settitle:@ "Walk" forstate:uicontrolstatenormal]; [Btnfoot addtarget:self Action: @selector (Walkbtnclick) forcontrolevents:uicontroleventtouchupinside]; [Self.view Addsubview:lablefrom]; [Self.view Addsubview:lableto]; [Self.view AddSubview:textfrom]; [Self.view Addsubview:textto]; [Self.view Addsubview:btnbus]; [Self.view Addsubview:btncar]; [Self.view Addsubview:btnfoot]; CGFloat height = [UIScreen mainscreen].bounds.size.height-cgrectgetmaxy (btnbus.frame); _MAPV = [[UIView alloc] InitWith Frame:cgrectmake (0, Cgrectgetmaxy (btnbus.frame), (+), height)];_mapv.backgroundcolor = [Uicolor Whitecolor]; [Self.view ADDSUBVIEW:_MAPV];

}

-(void) Walkbtnclick
{

bmkplannode* start = [[Bmkplannode alloc]init]; start.name = Textfrom.text;start.cityname = @ "Beijing"; bmkplannode* end = [[Bmkplannode alloc]init];end.name = Textto.text;end.cityname = @ "Beijing"; Bmkwalkingrouteplanoption *walkingroutesearchoption = [[Bmkwalkingrouteplanoption alloc]init]; Walkingroutesearchoption.from = Start;walkingroutesearchoption.to = end; NSLog (@ "%@------%@", start.name,end.name); BOOL flag = [_routesearch walkingsearch:walkingroutesearchoption];if (flag) {    NSLog (@ "Walk Retrieval sent successfully");} else{    NSLog (@ "Walk retrieve send Failed");}

}

  • (void) Ongetwalkingrouteresult: (Bmkroutesearch) Searcher Result: (BmkwalkingrouteresultResult 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];int size = [Plan.steps count];int    planpointcounts = 0;for (int i = 0; i < size; i++) {bmkwalkingstep* transitstep = [Plan.steps objectatindex:i];        if (i==0) {routeannotation* item = [[Routeannotation alloc]init];        Item.coordinate = plan.starting.location;        Item.title = @ "starting point";        Item.type = 0; [_mapview Addannotation:item];        Add Start Callout}else if (i==size-1) {routeannotation* item = [[Routeannotation alloc]init];        Item.coordinate = plan.terminal.location;        Item.title = @ "End point";        Item.type = 1; [_mapview Addannotation:item];    Add a start callout}//Add annotation node routeannotation* item = [[Routeannotation alloc]init];    Item.coordinate = transitStep.entrace.location;    Item.title = transitstep.entraceinstruction;    Item.degree = transitstep.direction * 30;    Item.type = 4;    [_mapview Addannotation:item]; Total number of trace points cumulative planpointcounts += Transitstep.pointscount;} Locus point Bmkmappoint * temppoints = new Bmkmappoint[planpointcounts];int i = 0;for (int j = 0; J < size; J + +) {Bmkwalki    ngstep* 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++; }}//build bmkpolylinebmkpolyline* polyLine by points = [Bmkpolyline polylinewithpoints:temppoints count:planpointcounts]; [_mapview Addoverlay:polyline]; Add route overlaydelete []temppoints;
    }

}

    • (Bmkoverlayview) Mapview: (Bmkmapview ) Map Viewforoverlay: (ID) Overlay
      {
      if ([Overlay Iskindofclass:[bmkpolyline class]]) {
      bmkpolylineview* Polylineview = [[Bmkpolylineview alloc] initwithoverlay:overlay];p olylineview.fillcolor = [[UIColor Cyancolor] colorwithalphacomponent:1];p olylineview.strokecolor = [[Uicolor bluecolor] colorwithalphacomponent:0.7]; Polylineview.linewidth = 3.0;return Polylineview;
      }
      return nil;
      }
Pragma mark-Here's the pin-changer!
  • (Bmkannotationview) Getrouteannotationview: (Bmkmapview ) Mapview viewforannotation: (routeannotation) routeannotation
    {
    Bmkannotationview
    view = nil;
    Switch (routeannotation.type) {

    Case 0:{view = [Mapview dequeuereusableannotationviewwithidentifier:@ "Start_node"]; if (view = = nil) {view = [[Bmkannotationview alloc]initwithannotation:routeannotation reuseidentifier:@] Start_node        "] ;        View.image = [UIImage imagewithcontentsoffile:[self getmybundlepath1:@ "Images/icon_nav_start.png"];        View.centeroffset = Cgpointmake (0,-(view.frame.size.height * 0.5));    View.canshowcallout = TRUE;    } view.annotation = Routeannotation;}    Break;case 1:{view = [Mapview dequeuereusableannotationviewwithidentifier:@ "End_node"];  if (view = = nil) {view = [[Bmkannotationview alloc]initwithannotation:routeannotation reuseidentifier:@ "End_node"]        ;        View.image = [UIImage imagewithcontentsoffile:[self getmybundlepath1:@ "Images/icon_nav_end.png"];        View.centeroffset = Cgpointmake (0,-(view.frame.size.height * 0.5));    View.canshowcallout = TRUE;    } view.annotation = Routeannotation;} Break;case 2:{view = [MapvieW dequeuereusableannotationviewwithidentifier:@ "Bus_node"];  if (view = = nil) {view = [[Bmkannotationview alloc]initwithannotation:routeannotation reuseidentifier:@ "Bus_node"]        ;        View.image = [UIImage imagewithcontentsoffile:[self getmybundlepath1:@ "Images/icon_nav_bus.png"];    View.canshowcallout = TRUE;    } view.annotation = Routeannotation;}    Break;case 3:{view = [Mapview dequeuereusableannotationviewwithidentifier:@ "Rail_node"]; if (view = = nil) {view = [[Bmkannotationview alloc]initwithannotation:routeannotation reuseidentifier:@ "Rail_node"        ] ;        View.image = [UIImage imagewithcontentsoffile:[self getmybundlepath1:@ "Images/icon_nav_rail.png"];    View.canshowcallout = TRUE;    } view.annotation = Routeannotation;}    Break;case 4:{view = [Mapview dequeuereusableannotationviewwithidentifier:@ "Route_node"]; if (view = = nil) {view = [[Bmkannotationview alloc]initwithannotation:routeannotation reuseidentifier:@] RoutE_node "];    View.canshowcallout = TRUE;    } else {[view setneedsdisplay];    } uiimage* image = [UIImage imagewithcontentsoffile:[self getmybundlepath1:@ "Images/icon_direction.png"];    View.image = [Image imageRotatedByDegrees:routeAnnotation.degree];    View.annotation = routeannotation;}    Break;case 5:{view = [Mapview dequeuereusableannotationviewwithidentifier:@ "Waypoint_node"]; if (view = = nil) {view = [[Bmkannotationview alloc]initwithannotation:routeannotation reuseidentifier:@] Waypoint_n        Ode "];    View.canshowcallout = TRUE;    } else {[view setneedsdisplay];    } uiimage* image = [UIImage imagewithcontentsoffile:[self getmybundlepath1:@ "Images/icon_nav_waypoint.png"];    View.image = [Image imageRotatedByDegrees:routeAnnotation.degree];    View.annotation = routeannotation;} Break;default:break;

    }

    return view;
    }

  • (Bmkannotationview ) Mapview: (Bmkmapview ) View viewforannotation: (ID) annotation
    {
    if ([Annotation iskindofclass:[routeannotation class]]) {

    return [Self Getrouteannotationview:view viewforannotation: (routeannotation*) annotation];

    }
    return nil;
    }

  • (void) didreceivememorywarning
    {
    [Super didreceivememorywarning];
    Dispose of any resources the can be recreated.
    }
    @end

and _routesearch.delegate = self; When setting up the agent, using the agent in the Bmkroutesearch Baidu API, and this agent must first implement the Proxy method to set up the agent (generally our agent method, do not need to abide by Oh!) And we are using arc, so this line of code will be an error! The Proxy property must be set to weak!

Other basically nothing wrong ah, other can not refer to the official demo Oh!

iOS Baidu Map-Path planning

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.