iOS 自定義百度地圖圖標(biāo)

提示:文章只是用來(lái)記錄本人自己在學(xué)習(xí)過程中所遇到的一些問題的解決方案,如果有什么意見可以留言提出來(lái),不喜勿噴哦!

時(shí)間有腳

百度地圖的簡(jiǎn)單使用

提示:我這里有使用到 storyboard

  • 首先你需要導(dǎo)入百度地圖的相關(guān)包,這些都可以在百度地圖官方API里下載,然后就是在要展示百度地圖的類里引入你需要的頭文件,繼承其相關(guān) 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];
  • 進(jìn)行相關(guān)設(shè)置(這里的這個(gè) "icon_nav_start" 就是自己定義的當(dāng)前位置大頭針圖片
-(void)viewWillAppear:(BOOL)animated {
    [_mapView viewWillAppear];
    _mapView.delegate = self; // 此處記得不用的時(shí)候需要置nil,否則影響內(nèi)存的釋放
    _locService.delegate = self;
}

- (void)viewDidAppear:(BOOL)animated{
    BMKLocationViewDisplayParam *displayParam = [[BMKLocationViewDisplayParam alloc]init];
    displayParam.isRotateAngleValid = true;//跟隨態(tài)旋轉(zhuǎn)角度是否生效
    displayParam.isAccuracyCircleShow = false;//精度圈是否顯示
    displayParam.locationViewImgName= @"icon_nav_start";//定位圖標(biāo)名稱
    [_mapView updateLocationViewWithParam:displayParam];
}

-(void)viewWillDisappear:(BOOL)animated {
    [_mapView viewWillDisappear];
    _mapView.delegate = nil; // 不用時(shí),置nil
    _locService.delegate = nil;
}
  • 定位回調(diào)
#pragma mark - 定位回調(diào)
//實(shí)現(xiàn)相關(guān)delegate 處理位置信息更新
//處理方向變更信息
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    //[_mapView updateLocationData:userLocation];
}
//處理位置坐標(biāo)更新
- (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;


        
        //發(fā)起反向地理編碼檢索
        CLLocationCoordinate2D pt = _coordinate;
        BMKReverseGeoCodeOption *reverseGeoCodeSearchOption = [[
        BMKReverseGeoCodeOption alloc]init];
        reverseGeoCodeSearchOption.reverseGeoPoint = pt;
        BOOL flag = [_searcher reverseGeoCode:reverseGeoCodeSearchOption];
        if(flag)
        {
          NSLog(@"反geo檢索發(fā)送成功");
        [_locService stopUserLocationService];
        }
        else
        {
          NSLog(@"反geo檢索發(fā)送失敗");    
        }
    }
}

#pragma mark - 反向地理編碼檢索回調(diào)
-(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(@"抱歉,未找到結(jié)果");
  }
}

這里對(duì)于這個(gè)反向地址編碼回調(diào)里面的內(nèi)容我有必要說(shuō)明一下:由于項(xiàng)目需要根據(jù)當(dāng)前位置去請(qǐng)求周圍的其他大頭針位置,所以這里其實(shí)是一個(gè)請(qǐng)求,用來(lái)去獲取其他大頭針位置,你可以選擇忽略!

  • 大頭針以及氣泡自定義
#pragma mark - 顯示大頭針
/**
 *根據(jù)anntation生成對(duì)應(yīng)的View
 *@param mapView 地圖View
 *@param annotation 指定的標(biāo)注
 *@return 生成的標(biāo)注View
 */
- (BMKAnnotationView *)mapView:(BMKMapView *)view viewForAnnotation:(id <BMKAnnotation>)annotation
{
    if([annotation isKindOfClass:[BMKPinAnnotationView class]]){
        BMKAnnotationView* annotationView = [view dequeueReusableAnnotationViewWithIdentifier:@"xidanMark"];
        NSLog(@"用戶位置圖標(biāo)!");
        return annotationView;
    }else{
        // 生成重用標(biāo)示identifier
        NSString *AnnotationViewID = @"xidanMark";
        // 檢查是否有重用的緩存
        BMKAnnotationView* annotationView = [view dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
        // 緩存沒有命中,自己構(gòu)造一個(gè),一般首次添加annotation代碼會(huì)運(yùn)行到此處
        if (annotationView == nil) {
            annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
            ((BMKPinAnnotationView*)annotationView).pinColor = BMKPinAnnotationColorRed;
            // 設(shè)置重天上掉下的效果(annotation)
            ((BMKPinAnnotationView*)annotationView).animatesDrop = YES;
        }
        // 設(shè)置位置
        annotationView.centerOffset = CGPointMake(0, -(annotationView.frame.size.height * 0.5));
        annotationView.annotation = annotation;
        // 單擊彈出泡泡,彈出泡泡前提annotation必須實(shí)現(xiàn)title屬性
        annotationView.canShowCallout = NO;
        // 設(shè)置是否可以拖拽
        annotationView.draggable = NO;
        // 設(shè)置大頭針圖標(biāo)
        annotationView.image=[UIImage imageNamed:@"siteGreen"];
        return annotationView;
    }
}

#pragma mark 選中大頭針的時(shí)候,彈出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)
            {//獲取到當(dāng)前的大頭針 你可以執(zhí)行一些操作
                _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:@"無(wú)"];
                }else{
                    _discount.text =  [NSString stringWithFormat:@"%@", _array[i][@"DisCount"]];
                }
                _numForAll.text = [NSString stringWithFormat:@"%@ 臺(tái)", _array[i][@"SumOfTotalPoint"]];
                _numForFree.text = [NSString stringWithFormat:@"%@ 臺(tái)", _array[i][@"FreeSumOfPoint"]];
                //計(jì)算距離
                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 點(diǎn)擊地圖空白旳地方時(shí)候
-(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 關(guān)聯(lián)。_annotationArray 為從后臺(tái)請(qǐng)求到的周圍大頭針數(shù)據(jù)。

  • 氣泡視圖


    storyboard自定義氣泡視圖

這里我為了圖個(gè)方便就直接使用的 storyboard 自定義視圖,實(shí)際中也可以通過代碼實(shí)現(xiàn)。

以上就是我整個(gè)自定義百度地圖的實(shí)現(xiàn)!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容