美文网首页百度地图轨迹绘制iOS学习iOS学习开发
ios 百度地图(开启百度地图之旅 3 划线 导航 大头针常

ios 百度地图(开启百度地图之旅 3 划线 导航 大头针常

作者: 夕儿77 | 来源:发表于2016-12-10 15:33 被阅读464次

    上篇开启百度之旅 2

    一 补充大头针和气泡常用的方法

    1.1 初始化大头针给大头针标题
    pointAnnotation = [[BMKPointAnnotation alloc] init];;
    pointAnnotation.title = @“今天天气不错“;
    1.2 点击大头针方法
    - (void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view {
        
          NSLog(@"点击大头针");
    }
    
    
    1.3 点击气泡方法
    - (void)mapView:(BMKMapView *)mapView annotationViewForBubble:(BMKPointAnnotation *)view{
        NSLog(@"点击气泡");
    }
    

    二 定位到当前位置 地图画线(公交划线为例)

    2.1代理<BMKMapViewDelegate, BMKRouteSearchDelegate,BMKLocationServiceDelegate>
    2.2 导入头文件
    #import <BaiduMapAPI_Map/BMKMapView.h>//只引入所需的单个头文件

    #######import <BaiduMapAPI_Map/BMKMapComponent.h>
    #######import <BaiduMapAPI_Search/BMKSearchComponent.h>
    #######import <BaiduMapAPI_Location/BMKLocationComponent.h>//引入定位功能所有的头文件
    #######import "UIImage+Rotate.h"(在百度地图Demo中找到拖到自己的工程中)
    #######import "RouteAnnotation.h"(在百度地图Demo中找到拖到自己的工程中)

    2.3 设置
    //需要注意把.m文件改成.mm文件
    #define MYBUNDLE_NAME @ "mapapi.bundle"
    #define MYBUNDLE_PATH [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent: MYBUNDLE_NAME]
    #define MYBUNDLE [NSBundle bundleWithPath: MYBUNDLE_PATH]
    #define BMKSPAN 0.02
    
    
    2.4
    {
         int _type; ///<0:起点 1:终点 2:公交 3:地铁 4:驾乘 5:途经点
         int _degree;
         BMKRouteSearch* _routesearch;
         BMKLocationService* _locService;
    }
    @property (nonatomic) int type;
    @property (nonatomic) int degree;
    @property (strong, nonatomic) IBOutlet BMKMapView *mapView;
    @property (nonatomic,assign) CLLocationCoordinate2D coor;
    
    
    2.4
      //适配ios7
        if( ([[[UIDevice currentDevice] systemVersion] doubleValue]>=7.0))
        {
            self.navigationController.navigationBar.translucent = NO;
        }
        _mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 0, WIDTH,HEIGHT)];
        _mapView.delegate = self;
       //初始化BMKRouteSearch
        _routesearch = [[BMKRouteSearch alloc] init];
       
        //初始化BMKLocationService(定位)
        _locService = [[BMKLocationService alloc]init];
        _locService.delegate = self;
        //启动LocationService
        [_locService startUserLocationService];
        _mapView.showsUserLocation = YES;//显示定位图层
        _mapView.showsUserLocation = NO;
        _mapView.userTrackingMode = BMKUserTrackingModeNone;
        _mapView.showsUserLocation = YES;
        [self.view addSubview:_mapView];
     
    
    2.5
    -(void)viewWillAppear:(BOOL)animated {
        [_mapView viewWillAppear];
        _mapView.delegate = self; // 此处记得不用的时候需要置nil,否则影响内存的释放
        _routesearch.delegate = self; // 此处记得不用的时候需要置nil,否则影响内存的释放
    }
    
    -(void)viewWillDisappear:(BOOL)animated {
        [_mapView viewWillDisappear];
        _mapView.delegate = nil; // 不用时,置nil
        _routesearch.delegate = nil; // 不用时,置nil
    }
    
    - (void)dealloc {
        if (_routesearch != nil) {
            _routesearch = nil;
        }
        if (_mapView) {
            _mapView = nil;
        }
    }
    
    
    2.6以下是划线必备
    #pragma mark - BMKMapViewDelegate
    
    - (BMKAnnotationView *)mapView:(BMKMapView *)view viewForAnnotation:(id <BMKAnnotation>)annotation
    {
        if ([annotation isKindOfClass:[RouteAnnotation class]]) {
            return [self getRouteAnnotationView:view viewForAnnotation:(RouteAnnotation*)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 = 5.0;
            return polylineView;
        }
        return nil;
    }
    
    #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){
                    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]; // 添加起点标注
                }
                RouteAnnotation* item = [[RouteAnnotation 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];
        }
    }
    
    - (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;
    }
    
    #pragma mark - 私有
    
    - (NSString*)getMyBundlePath1:(NSString *)filename
    {
        
        NSBundle * libBundle = MYBUNDLE ;
        if ( libBundle && filename ){
            NSString * s=[[libBundle resourcePath ] stringByAppendingPathComponent : filename];
            return s;
        }
        return nil ;
    }
    
    
    //根据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;
            }
        }
        _mapView.zoomLevel = _mapView.zoomLevel - 0.3;
    }
    
    2.7 开始画线
    //定位
    
    
    /**
     *用户位置更新后,会调用此函数
     *@param userLocation 新的用户位置
     */
    - (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
    {   [_locService stopUserLocationService];
        NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
        
        CLLocation *location=[[CLLocation alloc]initWithLatitude:userLocation.location.coordinate.latitude longitude:userLocation.location.coordinate.longitude];
        //获得一个合适的区域
        CLLocationCoordinate2D center = CLLocationCoordinate2DMake(location.coordinate.latitude,location.coordinate.longitude);
        BMKCoordinateSpan span;
        
        span.latitudeDelta=BMKSPAN;
        
        span.longitudeDelta=BMKSPAN;
        
        BMKCoordinateRegion fitsRegion;
        
        fitsRegion.center=center;////限制地图显示范围
        
        fitsRegion.span=span;////限制地图显示范围
        #pragma mark -划线
        [self.mapView setRegion:fitsRegion animated:YES];
        BMKPlanNode* start = [[BMKPlanNode alloc]init];
        CLLocationCoordinate2D coor1;
        coor1.latitude = userLocation.location.coordinate.latitude;
        coor1.longitude = userLocation.location.coordinate.longitude;;
        start.pt = coor1;
        start.name = @"起点";
        start.cityName = @"郑州";
        _coor = coor1;
        
        BMKPlanNode* end = [[BMKPlanNode alloc]init];
        CLLocationCoordinate2D coor2;
        coor2.latitude = 34.721647;
        coor2.longitude = 113.710344;
        end.pt = coor2;
        end.cityName = @"郑州";
        end.name =@"终点";
        BMKTransitRoutePlanOption *transitRouteSearchOption = [[BMKTransitRoutePlanOption alloc]init];
        transitRouteSearchOption.city= @"郑州";
        transitRouteSearchOption.from = start;
        transitRouteSearchOption.to = end;
        BOOL flag = [_routesearch transitSearch:transitRouteSearchOption];
        
        if(flag)
        {
            NSLog(@"bus检索发送成功");
        }
        else
        {
            NSLog(@"bus检索发送失败");
        }
        
        [_mapView updateLocationData:userLocation];
    }
    
    
    

    三 导航(调用百度客户端,没有客户端调取网页版)

    3.1导航配置
    //plish文件添加
     <key>LSApplicationQueriesSchemes</key>
        <array>
            <string>baidumap</string>
        </array>
    
    3.2导入头文件

    #######import <BaiduMapAPI_Utils/BMKUtilsComponent.h>

    3.3
       BMKOpenTransitRouteOption *opt = [[BMKOpenTransitRouteOption alloc] init];
        //    opt.appName = @"SDK调起Demo";
        opt.appScheme = @"baidumapsdk://mapsdk.baidu.com";
        //初始化起点节点
        BMKPlanNode* start = [[BMKPlanNode alloc]init];
        //指定起点经纬度
        CLLocationCoordinate2D coor1;
        coor1.latitude = _coor.latitude;
        coor1.longitude = _coor.longitude;
        //指定起点名称
        start.name = @"当前位置";
        start.pt = coor1;
        //指定起点
        opt.startPoint = start;
        
        //初始化终点节点
        BMKPlanNode* end = [[BMKPlanNode alloc]init];
        CLLocationCoordinate2D coor2;
        coor2.latitude = 34.721647;
        coor2.longitude = 113.710344;
        end.pt = coor2;
        //指定终点名称
        end.name =@"终点";
        opt.endPoint = end;
        
        BMKOpenErrorCode code = [BMKOpenRoute openBaiduMapTransitRoute:opt];
        NSLog(@"%d", code);
    

    相关文章

      网友评论

        本文标题:ios 百度地图(开启百度地图之旅 3 划线 导航 大头针常

        本文链接:https://www.haomeiwen.com/subject/fioymttx.html