搭建百度地图,步行路线、反地理编码等应用

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

    {

    //启动引擎 BaiduMapManager

    _mapManager = [[BMKMapManager alloc]init];

    // 如果要关注网络及授权验证事件,设定generalDelegate参数,否则为nil即可

    BOOL ret = [_mapManager start:@" 申请的有效key" generalDelegate: (id<BMKGeneralDelegate>)self];

    if (!ret) {

    NSLog(@”manager start failed!”);

    }

    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];

    // Override point for customization after application launch.

    self.viewController = [[[ViewController alloc] initWithNibName:@”ViewController” bundle:nil] autorelease];

    self.window.rootViewController = self.viewController;

    [self.window makeKeyAndVisible];

    return YES;

    }

用xib 或者手动创建一张地图

在 -(void)viewWillAppear:(BOOL)animated中 要设置代理(或者viewDidLoad的时候创建设置),切记,否则可能会出现方格 不出现地图。

_myMapView=[[BMKMapView alloc] initWithFrame:CGRectMake(0, 0, Screen.width, Screen.height)];

    [super viewWillAppear:animated];
    [_mapView viewWillAppear];
    _mapView.showsUserLocation = NO;//先关闭显示的定位图层
    _mapView.userTrackingMode = BMKUserTrackingModeNone;//设置定位的状态
    _mapView.showsUserLocation = YES;//显示定位图层
      _mapView.delegate = self;
    _geocodesearch.delegate = self;
    _userLocation.delegate = self;
    _walkingRoutePlanOption.delegate = self;

步行路线代理、定位代理等。


在退出界面的时候 (注意!不能在viewWillDisappear方法中,至于为什么 听别人说的 百度地图与ios会冲突)设置代理为空

        [_mapView viewWillDisappear];
        _mapView.delegate = nil;
        _geocodesearch.delegate = nil; // 此处记得不用的时候需要置nil,否则影响内存的释放
        _userLocation.delegate = nil;
        [_userLocation stopUserLocationService];
        _mapView.showsUserLocation = NO;
        _walkingRoutePlanOption.delegate = nil;

当你用到
/**
 *打开定位服务
 */
-(void)startUserLocationService;
的时候,就会回调代理方法

/**
 *用户方向更新后,会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation;

还有一些失败。停止定位等代理方法 请下载百度SDK查看。

-(void)didUpdateUserLocation:(BMKUserLocation *)userLocation{
    NSLog(@"latitude--%f,longtitude---%f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    CLLocationDegrees locaLatitude;
    CLLocationDegrees locaLongitude;
    locaLatitude=userLocation.location.coordinate.latitude;//纬度
    locaLongitude=userLocation.location.coordinate.longitude;//精
    BMKCoordinateRegion region;
    //将定位的点居中显示
    region.center.latitude=locaLatitude;
    region.center.longitude=locaLongitude;
    region.span.latitudeDelta  = 0.01;
    region.span.longitudeDelta = 0.01;
    [_mapView setRegion:region animated:NO];
    
    subCoor.latitude = locaLatitude;
    subCoor.longitude = locaLongitude;
    [_mapView setCenterCoordinate:subCoor animated:YES];
}

根据所得到的 经纬度 可以确定地理位置

[self geocode:[_latitude doubleValue] withLongitude:[_longitude doubleValue]];

-(void)geocode:(double)latitude withLongitude:(double)longitude{
    
    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){0, 0};
    pt = (CLLocationCoordinate2D){latitude, longitude};
    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    reverseGeocodeSearchOption.reverseGeoPoint = pt;
    BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];
    
    if(flag)
    {
        NSLog(@"反geo检索发送成功");
    }
    else
    {
        NSLog(@"反geo检索发送失败");
    }
}

其中 
/**
 *根据地理坐标获取地址信息
 *异步函数,返回结果在BMKGeoCodeSearchDelegate的onGetAddrResult通知
 *@param reverseGeoCodeOption 反geo检索信息类
 *@return 成功返回YES,否则返回NO
 */
- (BOOL)reverseGeoCode:(BMKReverseGeoCodeOption*)reverseGeoCodeOption;
然后会调用
/**
 *返回反地理编码搜索结果
 *@param searcher 搜索对象
 *@param result 搜索结果
 *@param error 错误号,@see BMKSearchErrorCode
 */
- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error;
则为
-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
	if (error == 0) {
        //
        self.addArr = [NSString stringWithFormat:@"%@",result.address];
        _pointAnnotation.subtitle =[NSString stringWithFormat:@"当前位置:%@",self.addArr];
        if (_pointAnnotation == nil) {
            [XCCommonUtility QQTShowAlertMsg:@"无法获取当前位置,请稍后再试"];
            return ;
        }
        [annotationArrays addObject:_pointAnnotation];
        [_mapView addAnnotations:annotationArrays];
        [self seachWalkRoute];
	}
}

PS:

result.address即为反地理编码得到的位置。    [annotationArrays addObject:_pointAnnotation]; 是为标注数组。当有多个标注,先把标注添加到数组里 然后再添加至

 [_mapView addAnnotations:annotationArrays];文章末尾会说明。

/**
 *向地图窗口添加标注,需要实现BMKMapViewDelegate的-mapView:viewForAnnotation:函数来生成标注对应的View
 *@param annotation 要添加的标注
 */
- (void)addAnnotation:(id <BMKAnnotation>)annotation;

/**
 *向地图窗口添加一组标注,需要实现BMKMapViewDelegate的-mapView:viewForAnnotation:函数来生成标注对应的View
 *@param annotations 要添加的标注数组
 */
- (void)addAnnotations:(NSArray *)annotations;


步行路线

/**
 *步行路线检索
 *异步函数,返回结果在BMKRouteSearchDelegate的onGetWalkingRouteResult通知
 *@param walkingRoutePlanOption 步行检索信息类
 *@return 成功返回YES,否则返回NO
 */
-(BOOL)walkingSearch:(BMKWalkingRoutePlanOption*)walkingRoutePlanOption;
/**
 *返回步行搜索结果
 *@param searcher 搜索对象
 *@param result 搜索结果,类型为BMKWalkingRouteResult
 *@param error 错误号,@see BMKSearchErrorCode
 */
-(void)onGetWalkingRouteResult:(BMKRouteSearch*)searcher result:(BMKWalkingRouteResult*)result errorCode:(BMKSearchErrorCode)error;

直接上代码

-(void)seachWalkRoute{
    BMKWalkingRoutePlanOption *walkingRoute = [[BMKWalkingRoutePlanOption alloc]init];
    
    BMKPlanNode* currentNode = [[BMKPlanNode alloc] init];
    currentNode.pt = mianCoor;
    //    currentNode.name = @"aaa"; //注意,这里不能为空@""
    BMKPlanNode* poiNode = [[BMKPlanNode alloc] init];
    poiNode.pt = subCoor;
    //    poiNode.name = @"bbb";//注意,这里不能为空@""
    walkingRoute.from = currentNode;
    walkingRoute.to = poiNode;
    BOOL flag = [_walkingRoutePlanOption walkingSearch:walkingRoute];
    if (flag == YES) {
        NSLog(@"搜索成功");
    }else{
        [XCCommonUtility QQTShowAlertMsg:@"暂时无法获取步行路线"];
        NSLog(@"搜索失败");
    }
}
- (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){
                MapPointAnnotion* item = [[MapPointAnnotion alloc]init];
                item.coordinate = plan.starting.location;
                item.subtitle =_describe;;
                item.type = 0;
                item.tagNumber = 1;
                [_mapView addAnnotation:item]; // 添加起点标注
                
            }else if(i==size-1){
                MapPointAnnotion* item = [[MapPointAnnotion alloc]init];
                item.coordinate = plan.terminal.location;
                item.subtitle =[NSString stringWithFormat:@"当前位置:%@",self.addArr];;
                item.type = 1;
                item.tagNumber = 0;
                [_mapView addAnnotation:item]; // 添加起点标注
            }
            //添加annotation节点
            MapPointAnnotion* item = [[MapPointAnnotion 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;
        
	}
}

第二个方法基本上是直接照搬官方deom的 后面才发现原来这么方便。。刚开始全是自己研究,直到绘制步行路线这块 搞了很久 最后还没搞出来 就去照搬demo了  然后略微修改 分分钟搞定了。。



刚刚所提到的添加标注,可以在路线两端用到。

添加标注必须实现此代理

/**
 *根据anntation生成对应的View
 *@param mapView 地图View
 *@param annotation 指定的标注
 *@return 生成的标注View
 */
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation;
-(BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id<BMKAnnotation>)annotation
{
    BMKAnnotationView *newAnnotation =[mapView viewForAnnotation:annotation];
    
    if (newAnnotation==nil && [annotation isKindOfClass:[MapPointAnnotion class]])
    {
        MapPointAnnotion* pointAnnotation = (MapPointAnnotion*)annotation;
        NSString *AnnotationViewID = [NSString stringWithFormat:@"iAnnotation-%d",pointAnnotation.tagNumber];
        newAnnotation = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
        // 设置颜色
        newAnnotation.tag = pointAnnotation.tagNumber;
        ((BMKPinAnnotationView*)newAnnotation).pinColor = BMKPinAnnotationColorPurple;
        
        // 从天上掉下效果
        ((BMKPinAnnotationView*)newAnnotation).animatesDrop = NO;
        // 设置可拖拽
        ((BMKPinAnnotationView*)newAnnotation).draggable = NO;
        //设置大头针图标
        if (pointAnnotation.tagNumber == 0) {
            ((BMKPinAnnotationView*)newAnnotation).image = [UIImage imageNamed:@"map_mark_mylocation.png"];
        }else{
            ((BMKPinAnnotationView*)newAnnotation).image = [UIImage imageNamed:@"map_mark.png"];
        }
        UIView *popView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 220, 60)];
        popView.layer.cornerRadius = 3;//设置那个圆角的有多圆
        popView.layer.borderWidth = 1;//设置边框的宽度,当然可以不要
        popView.layer.borderColor = [[UIColor lightGrayColor] CGColor];//设置边框的颜色
        popView.layer.masksToBounds = YES;
        //    popView.backgroundColor = [QQTStringPlist colorPlistForKey:@"qqt_bc"];
        [popView setBackgroundColor:[[QQTStringPlist colorPlistForKey:@"qqt_bc"]colorWithAlphaComponent:0.5]];
        
        UILabel *carName = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 220, 60)];
        carName.text = [annotation subtitle];
        carName.font = [UIFont systemFontOfSize:14];
        carName.textColor = [UIColor blackColor];
        carName.lineBreakMode = kTextLineBreakByCharWrapping;
        carName.textAlignment = kTextAlignmentCenter;
        carName.numberOfLines = 0;
        [popView addSubview:carName];
        BMKActionPaopaoView *pView = [[BMKActionPaopaoView alloc]initWithCustomView:popView];
        pView.frame = CGRectMake(0, 0, 220, 63);
        ((BMKPinAnnotationView*)newAnnotation).paopaoView = nil;
        ((BMKPinAnnotationView*)newAnnotation).paopaoView = pView;
        [newAnnotation setSelected:YES];
    }
    return newAnnotation;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值