iOS 百度地圖定位簽到實現(xiàn)

寫在前面:
項目需求用到這個功能唤蔗,主要目的是實現(xiàn)老師設(shè)置位置簽到范圍探遵,學(xué)生在一定范圍內(nèi)進(jìn)行簽到的功能窟赏。功能如下方截圖:


屏幕快照 2019-01-28 上午10.29.26.png

簡要介紹:

下面記錄一下主要的實現(xiàn)流程,功能的實現(xiàn)主要是根據(jù)百度地圖開發(fā)者官網(wǎng)提供的api文檔箱季,各項功能之間組合涯穷。百度地圖的SDK現(xiàn)在分成了地圖功能和定位功能兩塊不同的SDK,BaiduMapAPI這個是基礎(chǔ)的地圖功能藏雏,BMKLocationKit這個是定位功能拷况。項目里實現(xiàn)定位簽到功能用的的SDK包括上面說的這兩個模塊,所以在用cocopods引入framework的時候掘殴,需要引入:#百度地圖 pod 'BMKLocationKit' pod 'BaiduMapKit'

功能實現(xiàn)

一赚瘦、在APPdelegate.m文件中引入:
#import <BaiduMapAPI_Base/BMKBaseComponent.h>
#import <BMKLocationKit/BMKLocationComponent.h>

加入功能代碼:

#pragma mark 百度地圖設(shè)置
- (void)configBaiduMap {
    NSString *ak = @"xxxx";
    BMKMapManager *mapManager = [[BMKMapManager alloc] init];
    self.mapManager = mapManager;
    BOOL ret = [mapManager start:ak generalDelegate:nil];
    [[BMKLocationAuth sharedInstance] checkPermisionWithKey:ak authDelegate:self];
    if (!ret) {
        NSLog(@"manager start failed!");
    } 
}
二、在用到地圖定位功能的viewController中
#import <BMKLocationKit/BMKLocationComponent.h>
#import <BaiduMapAPI_Base/BMKBaseComponent.h>//引入base相關(guān)所有的頭文件
#import <BaiduMapAPI_Map/BMKMapComponent.h>//引入地圖功能所有的頭文件
遵循協(xié)議<BMKMapViewDelegate,BMKLocationManagerDelegate>
聲明全局變量
@property (nonatomic, strong) BMKUserLocation *userLocation; //當(dāng)前位置對象
@property (nonatomic, strong) BMKLocationManager *locationManager;/** locationManager*/
@property (nonatomic, strong) BMKMapView *mapView;/** 百度地圖*/
//@property (nonatomic, strong) BMKPointAnnotation* annotation ;/** 標(biāo)記*/
@property (nonatomic, strong) NSMutableArray *annotationArr;/** 標(biāo)記數(shù)組*/
@property (nonatomic, strong) NSMutableArray *circleArr;/** 圓形數(shù)組*/

地圖SDK文檔中建議在以下代碼中如此設(shè)置杯巨, 目的是控制內(nèi)存

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [_mapView viewWillAppear];
    _mapView.delegate = self;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [_mapView viewWillDisappear];
    _mapView.delegate = nil;
}

- (void)dealloc {
    if (_mapView) {
        _mapView = nil;
    }
}

初始化數(shù)組蚤告,這兩個數(shù)組在接下來會用到

- (NSMutableArray *)annotationArr {
 
    if (!_annotationArr) {
        _annotationArr = [NSMutableArray array];
    }
    return _annotationArr;
}

- (NSMutableArray *)circleArr {
    if (!_circleArr) {
        _circleArr = [NSMutableArray array];
    }
    return _circleArr;
}

添加地圖view

#pragma mark 添加地圖
- (void)addSignMapBgView {
    if (!self.mapBgView) {
        UIView *mapBgView = [UIView new];
        self.mapBgView = mapBgView;
        mapBgView.backgroundColor = [CommUtls colorWithHexString:APP_BgColor];
        [self addSubview:mapBgView];
        [mapBgView makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.tipView.bottom);
            make.left.right.bottom.equalTo(0);
        }];
        
        _mapView = [[BMKMapView alloc] initWithFrame:CGRectZero];
//        _mapView.delegate = self;
        [_mapView setZoomLevel:21];//精確到5米
        _mapView.showsUserLocation = YES;//顯示定位圖層
        [mapBgView addSubview:_mapView];
        [_mapView makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(0);
        }];
        _mapView.userTrackingMode = BMKUserTrackingModeNone;
        
    }

}

初始化地圖定位:這里我用的是一次定位而沒有選擇持續(xù)定位。

#pragma mark 初始化locationManager
- (void)initUserLocationManager {
    //因為mapView是在一個分離出來的view中創(chuàng)建的服爷,所以在這里將signSetTypeView中的mapView賦給當(dāng)前viewcontroller的mapView杜恰;
    self.mapView = self.mainView.signSetTypeView.mapView;
    self.mapView.delegate = self;
//    self.annotation = [[BMKPointAnnotation alloc] init];
    
    // self.mapView是BMKMapView對象
    //精度圈設(shè)置
    BMKLocationViewDisplayParam *param = [[BMKLocationViewDisplayParam alloc] init];
    //設(shè)置顯示精度圈,默認(rèn)YES
    param.isAccuracyCircleShow = YES;
    //精度圈 邊框顏色
    param.accuracyCircleStrokeColor = [UIColor colorWithRed:242/255.0 green:129/255.0 blue:126/255.0 alpha:1];
    //精度圈 填充顏色
    param.accuracyCircleFillColor = [UIColor colorWithRed:242/255.0 green:129/255.0 blue:126/255.0 alpha:0.3];
    [self.mapView updateLocationViewWithParam:param];
    
    self.userLocation = [[BMKUserLocation alloc] init];
    //初始化實例
    _locationManager = [[BMKLocationManager alloc] init];
    //設(shè)置delegate
    _locationManager.delegate = self;
    //設(shè)置返回位置的坐標(biāo)系類型
    _locationManager.coordinateType = BMKLocationCoordinateTypeBMK09LL;
    //設(shè)置距離過濾參數(shù)
    _locationManager.distanceFilter = kCLDistanceFilterNone;
    //設(shè)置預(yù)期精度參數(shù)
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    //設(shè)置應(yīng)用位置類型
    _locationManager.activityType = CLActivityTypeAutomotiveNavigation;
    //設(shè)置是否自動停止位置更新
    _locationManager.pausesLocationUpdatesAutomatically = NO;
    //設(shè)置是否允許后臺定位
    //_locationManager.allowsBackgroundLocationUpdates = YES;
    //設(shè)置位置獲取超時時間
    _locationManager.locationTimeout = 15;
    //設(shè)置獲取地址信息超時時間
    _locationManager.reGeocodeTimeout = 15;
    //請求一次定位
    [self requestLocation];
}

請求定位仍源,獲取經(jīng)緯度

#pragma mark 請求定位
- (void)requestLocation {
    
    [_locationManager requestLocationWithReGeocode:YES withNetworkState:YES completionBlock:^(BMKLocation * _Nullable location, BMKLocationNetworkState state, NSError * _Nullable error) {
        if (error)
        {
            NSLog(@"locError:{%ld - %@};", (long)error.code, error.localizedDescription);
        }
        if (location) {//得到定位信息心褐,添加annotation
            
            if (location.location) {
                NSLog(@"LOC = %@",location.location);
            }
            if (location.rgcData) {
                NSLog(@"rgc = %@",[location.rgcData description]);
            }
            
            if (!location) {
                return;
            }
            if (!self.userLocation) {
                self.userLocation = [[BMKUserLocation alloc] init];
            }
            self.userLocation.location = location.location;
            [self.mapView updateLocationData:self.userLocation];
            CLLocationCoordinate2D mycoordinate = location.location.coordinate;
            self.mapView.centerCoordinate = mycoordinate;
            
            //賦予初始值
            self.viewModel.lat = [NSString stringWithFormat:@"%f", location.location.coordinate.latitude];
            self.viewModel.lng = [NSString stringWithFormat:@"%f",location.location.coordinate.longitude];
            self.viewModel.radius = @"50";
            
            //打印經(jīng)緯度
            NSLog(@"didUpdateUserLocation lat %f,long %f",location.location.coordinate.latitude,location.location.coordinate.longitude);
        }
        NSLog(@"netstate = %d",state);
    }];
}

地圖長按選點功能實現(xiàn):

//長按地圖選點
- (void)mapview:(BMKMapView *)mapView onLongClick:(CLLocationCoordinate2D)coordinate {
    
    if (self.annotationArr.count > 0) {
        [mapView removeAnnotations:self.annotationArr];
        [self.annotationArr removeAllObjects];
        
        BMKPointAnnotation *annotation = [[BMKPointAnnotation alloc]init];
        annotation.coordinate = coordinate;
        [self.annotationArr addObject:annotation];
        [mapView addAnnotations:self.annotationArr];
    } else {
        BMKPointAnnotation *annotation = [[BMKPointAnnotation alloc]init];
        annotation.coordinate = coordinate;
        [self.annotationArr addObject:annotation];
        [mapView addAnnotations:self.annotationArr];
    }
    //彈出半徑選擇框
    [self showLocationSelectRadiusViewWithCoordinate:coordinate];
}

選點后彈出選擇定位范圍彈框

#pragma mark 彈出位置彈框
- (void)showLocationSelectRadiusViewWithCoordinate:(CLLocationCoordinate2D)coordinate {
    ExtraActLocationSignPopView *popView = [ExtraActLocationSignPopView new];
    [popView show];
    @weakify(self);
    [popView.locatioonSureSignal subscribeNext:^(NSString *x) {
        @strongify(self);
        self.viewModel.radius = x;
        CGFloat radius = [x floatValue];
        [self circleWithCenterWithCoordinate2D:coordinate radius:radius];
    }];
}

設(shè)置好定位點以及半徑范圍后繪制范圍圈,開始的時候聲明的circleArr在這里用來盛放添加的區(qū)域圓形笼踩,在添加新的圓圈的時候逗爹,將之前舊的移除,保證每次繪制的范圍都是最新的嚎于,同理annotationArr也是這個功能掘而,因為API有提供的- (void)addOverlays:(NSArray *)overlays;這個方法:/** *向地圖窗口添加一組Overlay,需要實現(xiàn)BMKMapViewDelegate的-mapView:viewForOverlay:函數(shù)來生成標(biāo)注對應(yīng)的View *@param overlays 要添加的overlay數(shù)組 */

#pragma mark 添加區(qū)域圓形覆蓋
- (void)circleWithCenterWithCoordinate2D:(CLLocationCoordinate2D )coor radius:(CGFloat)radius {
    
    NSLog(@"coordinate lat %f,long %f",coor.latitude,coor.longitude);
    //賦予點擊選點值
    self.viewModel.lat = [NSString stringWithFormat:@"%f", coor.latitude];
    self.viewModel.lng = [NSString stringWithFormat:@"%f",coor.longitude];
    
    if (self.circleArr.count > 0) {
        [_mapView removeOverlays:self.circleArr];
        [self.circleArr removeAllObjects];
        
        BMKCircle *circle = [BMKCircle circleWithCenterCoordinate:coor radius:radius];
        [self.circleArr addObject:circle];
        [_mapView addOverlays:self.circleArr];
    } else {
        BMKCircle *circle = [BMKCircle circleWithCenterCoordinate:coor radius:radius];
        [self.circleArr addObject:circle];
        [_mapView addOverlays:self.circleArr];
    }
}

#pragma mark 重繪overlay
- (BMKOverlayView *)mapView:(BMKMapView *)mapView viewForOverlay:(id <BMKOverlay>)overlay{
    if ([overlay isKindOfClass:[BMKCircle class]]){
        BMKCircleView* circleView = [[BMKCircleView alloc] initWithOverlay:overlay];
        circleView.fillColor = [UIColor colorWithRed:33/255.0 green:196/255.0 blue:206/255.0 alpha:0.3];
        circleView.strokeColor = [UIColor colorWithRed:33/255.0 green:196/255.0 blue:206/255.0 alpha:1];
        circleView.lineWidth = 1.0;
        return circleView;
    }
    return nil;
}

至此于购,在地圖上選點進(jìn)行簽到功能基本實現(xiàn)袍睡,另外,關(guān)于 自定義的范圍圓圈的顏色肋僧,邊框大小都是可以自定義的斑胜,選點的標(biāo)記也是可以自定義的,官方文檔有說明

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末嫌吠,一起剝皮案震驚了整個濱河市止潘,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌辫诅,老刑警劉巖凭戴,帶你破解...
    沈念sama閱讀 217,734評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異泥栖,居然都是意外死亡簇宽,警方通過查閱死者的電腦和手機(jī)勋篓,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,931評論 3 394
  • 文/潘曉璐 我一進(jìn)店門吧享,熙熙樓的掌柜王于貴愁眉苦臉地迎上來栏账,“玉大人萄金,你說我怎么就攤上這事。” “怎么了争舞?”我有些...
    開封第一講書人閱讀 164,133評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長画侣。 經(jīng)常有香客問我数冬,道長,這世上最難降的妖魔是什么操灿? 我笑而不...
    開封第一講書人閱讀 58,532評論 1 293
  • 正文 為了忘掉前任锯仪,我火速辦了婚禮,結(jié)果婚禮上趾盐,老公的妹妹穿的比我還像新娘庶喜。我一直安慰自己,他們只是感情好救鲤,可當(dāng)我...
    茶點故事閱讀 67,585評論 6 392
  • 文/花漫 我一把揭開白布久窟。 她就那樣靜靜地躺著,像睡著了一般本缠。 火紅的嫁衣襯著肌膚如雪斥扛。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,462評論 1 302
  • 那天丹锹,我揣著相機(jī)與錄音稀颁,去河邊找鬼。 笑死楣黍,一個胖子當(dāng)著我的面吹牛匾灶,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播锡凝,決...
    沈念sama閱讀 40,262評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼粘昨,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了窜锯?” 一聲冷哼從身側(cè)響起张肾,我...
    開封第一講書人閱讀 39,153評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎锚扎,沒想到半個月后吞瞪,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,587評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡驾孔,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,792評論 3 336
  • 正文 我和宋清朗相戀三年芍秆,在試婚紗的時候發(fā)現(xiàn)自己被綠了惯疙。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,919評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡妖啥,死狀恐怖霉颠,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情荆虱,我是刑警寧澤蒿偎,帶...
    沈念sama閱讀 35,635評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站怀读,受9級特大地震影響诉位,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜菜枷,卻給世界環(huán)境...
    茶點故事閱讀 41,237評論 3 329
  • 文/蒙蒙 一苍糠、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧啤誊,春花似錦岳瞭、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,855評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至枫耳,卻和暖如春乏矾,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背迁杨。 一陣腳步聲響...
    開封第一講書人閱讀 32,983評論 1 269
  • 我被黑心中介騙來泰國打工钻心, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人铅协。 一個月前我還...
    沈念sama閱讀 48,048評論 3 370
  • 正文 我出身青樓捷沸,卻偏偏與公主長得像,于是被迫代替她去往敵國和親狐史。 傳聞我的和親對象是個殘疾皇子痒给,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,864評論 2 354

推薦閱讀更多精彩內(nèi)容