iOS 自定义百度地图图标

提示:文章只是用来记录本人自己在学习过程中所遇到的一些问题的解决方案,如果有什么意见可以留言提出来,不喜勿喷哦!

iOS 自定义百度地图图标_第1张图片
时间有脚

百度地图的简单使用

提示:我这里有使用到 storyboard

  • 首先你需要导入百度地图的相关包,这些都可以在百度地图官方API里下载,然后就是在要展示百度地图的类里引入你需要的头文件,继承其相关 delegate 。
  • 初始化百度地图和定位
_mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds))];
_mapView.delegate = self;
[self.showMapView addSubview:_mapView];

_locService = [[BMKLocationService alloc]init];
_locService.delegate = self;
[_locService startUserLocationService];
  • 进行相关设置(这里的这个 "icon_nav_start" 就是自己定义的当前位置大头针图片
-(void)viewWillAppear:(BOOL)animated {
    [_mapView viewWillAppear];
    _mapView.delegate = self; // 此处记得不用的时候需要置nil,否则影响内存的释放
    _locService.delegate = self;
}

- (void)viewDidAppear:(BOOL)animated{
    BMKLocationViewDisplayParam *displayParam = [[BMKLocationViewDisplayParam alloc]init];
    displayParam.isRotateAngleValid = true;//跟随态旋转角度是否生效
    displayParam.isAccuracyCircleShow = false;//精度圈是否显示
    displayParam.locationViewImgName= @"icon_nav_start";//定位图标名称
    [_mapView updateLocationViewWithParam:displayParam];
}

-(void)viewWillDisappear:(BOOL)animated {
    [_mapView viewWillDisappear];
    _mapView.delegate = nil; // 不用时,置nil
    _locService.delegate = nil;
}
  • 定位回调
#pragma mark - 定位回调
//实现相关delegate 处理位置信息更新
//处理方向变更信息
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    //[_mapView updateLocationData:userLocation];
}
//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    if(_coordinate.latitude==0){
        NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
        
        _coordinate.latitude = userLocation.location.coordinate.latitude;
        _coordinate.longitude = userLocation.location.coordinate.longitude;
        
        _mapView.showsUserLocation = YES;//显示定位图层
        [_mapView updateLocationData:userLocation];
        
        _mapView.centerCoordinate = _coordinate;


        
        //发起反向地理编码检索
        CLLocationCoordinate2D pt = _coordinate;
        BMKReverseGeoCodeOption *reverseGeoCodeSearchOption = [[
        BMKReverseGeoCodeOption alloc]init];
        reverseGeoCodeSearchOption.reverseGeoPoint = pt;
        BOOL flag = [_searcher reverseGeoCode:reverseGeoCodeSearchOption];
        if(flag)
        {
          NSLog(@"反geo检索发送成功");
        [_locService stopUserLocationService];
        }
        else
        {
          NSLog(@"反geo检索发送失败");    
        }
    }
}

#pragma mark - 反向地理编码检索回调
-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
  if (error == BMK_SEARCH_NO_ERROR) {
     NSString *cityName = result.addressDetail.city;
    cityName=[cityName stringByReplacingOccurrencesOfString:@"市" withString:@""];
     NSString *inputParam = [StringToJsonUtility initAddressParamData:cityName Status:@""];
//     [_soap clearValues];
//     [_soap setValue:inputParam forKey:@"addressParam"];
//     [_soap requestURL:WebService_asmx soapAction:WebService_AddressService];
//     _soapAgent = @"AddressService";
//       NSString * headstr = [StringToJsonUtility initHeadParamData:_loginUser password:_password];
//      [_soapClient getDataAPIResultWithURL:WebService_asmx
//                              headerParams:headstr
//                                    params:inputParam
//                               htttpMethod:@"POST"
//                            withSOAPAction:WebService_AddressService
//                            withMethodName:@"AddressService"
//                              withParamKey:@"addressParam"
//                           withResultBlock:^(id result, BOOL isDictionary,id message) {
 //                              //[weakSelf ];
                               
 //                          }];
      
  }
  else {
      NSLog(@"抱歉,未找到结果");
  }
}

这里对于这个反向地址编码回调里面的内容我有必要说明一下:由于项目需要根据当前位置去请求周围的其他大头针位置,所以这里其实是一个请求,用来去获取其他大头针位置,你可以选择忽略!

  • 大头针以及气泡自定义
#pragma mark - 显示大头针
/**
 *根据anntation生成对应的View
 *@param mapView 地图View
 *@param annotation 指定的标注
 *@return 生成的标注View
 */
- (BMKAnnotationView *)mapView:(BMKMapView *)view viewForAnnotation:(id )annotation
{
    if([annotation isKindOfClass:[BMKPinAnnotationView class]]){
        BMKAnnotationView* annotationView = [view dequeueReusableAnnotationViewWithIdentifier:@"xidanMark"];
        NSLog(@"用户位置图标!");
        return annotationView;
    }else{
        // 生成重用标示identifier
        NSString *AnnotationViewID = @"xidanMark";
        // 检查是否有重用的缓存
        BMKAnnotationView* annotationView = [view dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
        // 缓存没有命中,自己构造一个,一般首次添加annotation代码会运行到此处
        if (annotationView == nil) {
            annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
            ((BMKPinAnnotationView*)annotationView).pinColor = BMKPinAnnotationColorRed;
            // 设置重天上掉下的效果(annotation)
            ((BMKPinAnnotationView*)annotationView).animatesDrop = YES;
        }
        // 设置位置
        annotationView.centerOffset = CGPointMake(0, -(annotationView.frame.size.height * 0.5));
        annotationView.annotation = annotation;
        // 单击弹出泡泡,弹出泡泡前提annotation必须实现title属性
        annotationView.canShowCallout = NO;
        // 设置是否可以拖拽
        annotationView.draggable = NO;
        // 设置大头针图标
        annotationView.image=[UIImage imageNamed:@"siteGreen"];
        return annotationView;
    }
}

#pragma mark 选中大头针的时候,弹出POP画面
-(void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view{
    if([view isKindOfClass:[BMKPinAnnotationView class]]){
        
        _popUpView.frame=CGRectMake(0,self.view.frame.size.height-220, SCREENWIDTH, 170);
        for (int i=0; i<_annotationArray.count; i++)
        {
            if (view.annotation.coordinate.latitude ==((BMKPointAnnotation*)_annotationArray[i]).coordinate.latitude)
            {//获取到当前的大头针 你可以执行一些操作
                _address.text = [NSString stringWithFormat:@"%@", _array[i][@"Address"]];
                _price.text =  [NSString stringWithFormat:@"%.1f 元/度" ,[_array[i][@"Price"] floatValue]];
                if([@"0" isEqualToString:[NSString stringWithFormat:@"%@", _array[i][@"DisCount"]]]){
                    _discount.text =  [NSString stringWithFormat:@"无"];
                }else{
                    _discount.text =  [NSString stringWithFormat:@"%@", _array[i][@"DisCount"]];
                }
                _numForAll.text = [NSString stringWithFormat:@"%@ 台", _array[i][@"SumOfTotalPoint"]];
                _numForFree.text = [NSString stringWithFormat:@"%@ 台", _array[i][@"FreeSumOfPoint"]];
                //计算距离
                BMKMapPoint point1 = BMKMapPointForCoordinate(_coordinate);
                BMKMapPoint point2 = BMKMapPointForCoordinate(CLLocationCoordinate2DMake(view.annotation.coordinate.latitude, view.annotation.coordinate.longitude));
                CLLocationDistance distance = BMKMetersBetweenMapPoints(point1,point2);
                _distance.text = [NSString stringWithFormat:@"%.2f 公里",distance/1000];
                
                _chargeSetId = _array[i][@"Id"];
            }
        }
        
        _desCoordinate = [view.annotation coordinate];
        
        CATransition *animation = [CATransition animation];
        animation.duration = 0.5f;
        animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
        [self.view.layer addAnimation:animation forKey:@"animation"];
        [self.view addSubview:_popUpView];
        [self.view bringSubviewToFront:_popUpView];
    }else{
        NSLog(@"选中我的位置!");
        
    }
}
#pragma  mark 点击地图空白旳地方时候
-(void)mapView:(BMKMapView *)mapView onClickedMapBlank:(CLLocationCoordinate2D)coordinate{
    CATransition *animation = [CATransition animation];
    animation.duration = 0.5f;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
        animation.fillMode = kCAGravityTopRight;
        animation.type = kCATransitionFromTop;
    [self.view.layer addAnimation:animation forKey:@"animation"];
    [_popUpView removeFromSuperview];
    [_selectSubView removeFromSuperview];
}

其中: _popUpView 就是自定义的气泡视图,下面的 _address 、_price 等都是视图中的子元素,这里使用的 storyboard 关联。_annotationArray 为从后台请求到的周围大头针数据。

  • 气泡视图


    iOS 自定义百度地图图标_第2张图片
    storyboard自定义气泡视图

这里我为了图个方便就直接使用的 storyboard 自定义视图,实际中也可以通过代码实现。

以上就是我整个自定义百度地图的实现!

你可能感兴趣的:(iOS 自定义百度地图图标)