ios百度地图-路径规划

百度地图的路径规划功能,
在使用百度路径的时候,出现了一些小问题,在此,分享一下自己的最简单的一个路径小demo
当然,前面的百度配置问题,我就不和大家讲了,因为这方面的资料太多了!现在,我来介绍一下这个小demo

ios百度地图-路径规划

AppDelegate.m文件如下,

#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];
    // 如果要关注网络及授权验证事件,请设定 generalDelegate参数
    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;

}

然后,rootViewController.m文件如下,这里只有步行这个按钮有效果哦!

#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:起点 1:终点 2:公交 3:地铁 4:驾乘 5:途经点
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 initialization
    self.view.backgroundColor = [UIColor redColor];

    }
    return self;
    }

  • (void)viewDidLoad
    {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @“路径规划”;

    [self setUpUI];

    textFrom.text = @“*”;
    textTo.text = @“百度大厦”;

    routesearch = [[BMKRouteSearch alloc]init];
    routesearch.delegate = self;// 此处记得不用的时候需要置nil,否则影响内存的释放
    mapView = [[BMKMapView alloc]initWithFrame:mapV.bounds];
    mapView.delegate = self; // 此处记得不用的时候需要置nil,否则影响内存的释放
    [
    mapV addSubview:_mapView];

}

-(void)setUpUI
{

UILabel *lableFrom = [[UILabel alloc] initWithFrame:CGRectMake(20,70, 60, 30)];
lableFrom.text = @"起点";

UILabel *lableTo = [[UILabel alloc] initWithFrame:CGRectMake(20,120, 60, 30)];
lableTo.text = @"终点";

textFrom = [[UITextField alloc] initWithFrame:CGRectMake(100, 70, 80, 30)];
textFrom.backgroundColor = [UIColor greenColor];

textTo = [[UITextField alloc] initWithFrame:CGRectMake(100, 120, 80, 30)];
textTo.backgroundColor = [UIColor greenColor];


btnBus = [[UIButton alloc] initWithFrame:CGRectMake(20, 160, 40, 30)];
[btnBus setTitle:@"公交" forState:UIControlStateNormal];
btnCar = [[UIButton alloc] initWithFrame:CGRectMake(80, 160, 40, 30)];
[btnCar setTitle:@"驾车" forState:UIControlStateNormal];
btnfoot = [[UIButton alloc] initWithFrame:CGRectMake(150, 160, 40, 30)];
[btnfoot setTitle:@"步行" 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] initWithFrame:CGRectMake(0,   CGRectGetMaxY(btnBus.frame), 320, height)];
_mapV.backgroundColor = [UIColor whiteColor];
[self.view addSubview:_mapV];

}

-(void)walkBtnClick
{

BMKPlanNode* start = [[BMKPlanNode alloc]init] ;
start.name = textFrom.text;
start.cityName = @"北京市";
BMKPlanNode* end = [[BMKPlanNode alloc]init];
end.name = textTo.text;
end.cityName = @"北京市";

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检索发送成功");
}
else
{
    NSLog(@"walk检索发送失败");
}

}

  • (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];
    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 = @"起点";
            item.type = 0;
            [_mapView addAnnotation:item]; // 添加起点标注
    
        }else if(i==size-1){
            RouteAnnotation* item = [[RouteAnnotation alloc]init];
            item.coordinate = plan.terminal.location;
            item.title = @"终点";
            item.type = 1;
            [_mapView addAnnotation:item]; // 添加起点标注
    
        }
        //添加annotation节点
        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];
    
        //轨迹点总数累计
        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;
    }

}

  • (BMKOverlayView)mapView:(BMKMapView )map viewForOverlay:(id )overlay
    {
    if ([overlay isKindOfClass:[BMKPolyline class]]) {
    BMKPolylineView* polylineView = [[BMKPolylineView alloc] initWithOverlay:overlay];
    polylineView.fillColor = [[UIColor cyanColor] colorWithAlphaComponent:1];
    polylineView.strokeColor = [[UIColor blueColor] colorWithAlphaComponent:0.7];
    polylineView.lineWidth = 3.0;
    return polylineView;
    }
    return nil;
    }

pragma mark -这里是换大头针的把!

  • (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_node"] ;
            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 that can be recreated.
    }
    @end

而 _routesearch.delegate = self;在设置代理的时候,使用的是BMKRouteSearch百度api中的代理,而此代理必须先实现了代理方法才能设置代理(一般我们些的代理方法,并不需要先遵守哦!)而且我们使用的是arc,所以,这行代码会报错!必须把代理属性设置为weak才行哦!

其它基本上没有什么错误了哈,其它不会可以参考官方demo哦!

ios百度地图-路径规划

上一篇:android BaseAdapter java.lang.ArrayIndexOutOfBoundsException!!!!!!!!!


下一篇:py-day2-1 python 列表类 list的调用反法