//
//  BaiduLocationManager.m
//  patrol
//
//  Created by 曹云霄 on 2016/10/28.
//  Copyright © 2016年 上海勾芒科技有限公司. All rights reserved.
//

#import "BaiduLocationManager.h"

@implementation BaiduLocationManager


+ (instancetype)manager
{
    static BaiduLocationManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[BaiduLocationManager alloc]init];
    });
    return manager;
}

- (instancetype)init
{
    if (self = [super init]) {
        [self initializePositioningService];
    }
    return self;
}

#pragma mark - 初始化定位服务、反地理解析服务
- (void)initializePositioningService
{
    self.geographicSearch = [[BMKGeoCodeSearch alloc]init];
    self.service = [[BMKLocationService alloc]init];
    self.service.pausesLocationUpdatesAutomatically = NO;
    self.service.distanceFilter = 100;
}

#pragma mark - 开始定位
- (void)startPositioning
{
    [ToolsManager getLocationAuthorizationStatus];
    self.geographicSearch.delegate = self;
    self.service.delegate = self;
    [self.service startUserLocationService];
}

#pragma mark - 停止定位
- (void)stopPositioning
{
    self.geographicSearch.delegate = nil;
    self.service.delegate = nil;
    [self.service stopUserLocationService];
}

#pragma mark - <BMKLocationServiceDelegate>
/**
 *在将要启动定位时，会调用此函数
 */
- (void)willStartLocatingUser
{
    if ([self.locationDelegate respondsToSelector:@selector(startPositioning)]) {
        [self.locationDelegate startPositioning];
    }
}

/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    kUser.latitude = [NSString stringWithFormat:@"%lf",userLocation.location.coordinate.latitude];
    kUser.longitude = [NSString stringWithFormat:@"%lf",userLocation.location.coordinate.longitude];
    //** 反地理解析 */
    BMKReverseGeoCodeOption *CodeOption = [[BMKReverseGeoCodeOption alloc]init];
    CodeOption.reverseGeoPoint = userLocation.location.coordinate;
    [self.geographicSearch reverseGeoCode:CodeOption];
    if ([self.locationDelegate respondsToSelector:@selector(positioningSuccess:)]) {
        [self.locationDelegate positioningSuccess:userLocation];
    }
}

/**
 *定位失败后，会调用此函数
 *@param error 错误号
 */
- (void)didFailToLocateUserWithError:(NSError *)error
{
    if ([self.locationDelegate respondsToSelector:@selector(positioningError:)]) {
        [self.locationDelegate positioningError:error];
    }
}












@end
