博客> IOS:百度地图单例模式获取经纬度以及地址位置解析
IOS:百度地图单例模式获取经纬度以及地址位置解析
2017-12-12 00:25 评论:0 阅读:308 742724282
ios 单例模式获取经纬度

一、常规单例模式初始化 @interface UseLocationManager : NSObject

@property (strong, nonatomic) BMKLocationService locationService; @property (strong, nonatomic) BMKGeoCodeSearch locationSearch;

//城市名 @property (strong,nonatomic) NSString *cityName;

@property (nonatomic,strong) NSString *address;

//用户纬度 @property (nonatomic,assign) double userLatitude;

//用户经度 @property (nonatomic,assign) double userLongitude;

//用户位置 @property (strong,nonatomic) CLLocation *clloction;

//初始化单例

  • (UseLocationManager *)sharedInstance;

-(void)startLocation; -(void)stopLocation;

二、常规初始化单例模式

+(UseLocationManager )sharedInstance{ static UseLocationManager _instance=nil;

//通过GCD dispatch_once_t方法提高单例的效率 static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instance=[[self alloc]init]; }); return _instance; }

-(id)init{ if (self == [super init]) { [self initBMKUserLocation]; } return self; }

//初始化百度地图管理类 -(void)initBMKUserLocation{ _locationService=[[BMKLocationService alloc]init]; _locationService.delegate=self; _locationSearch=[[BMKGeoCodeSearch alloc]init]; _locationSearch.delegate=self; [self startLocation]; }

//开始定位 -(void)startLocation{ [_locationService startUserLocationService]; }

//停止定位 -(void)stopLocation{ [_locationService stopUserLocationService]; }

pragma BMKLocationServiceDelegate

/* 用户位置更新后,会调用此函数 @param userLocation 新的用户位置 / -(void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation{ _clloction=userLocation.location; _userLatitude=_clloction.coordinate.latitude; _userLongitude=_clloction.coordinate.longitude;

CLLocationCoordinate2D pt = (CLLocationCoordinate2D){userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude};
BMKReverseGeoCodeOption *options = [[BMKReverseGeoCodeOption alloc] init];
options.reverseGeoPoint = pt;

[self.locationSearch reverseGeoCode:options];

[self stopLocation];

}

//地址解析 -(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch )searcher result:(BMKReverseGeoCodeResult )result errorCode:(BMKSearchErrorCode)error{

if (error == BMK_SEARCH_NO_ERROR) {
    [self.locationService stopUserLocationService];
    self.locationService.delegate = nil;
    self.locationSearch.delegate = nil;

    _cityName=result.addressDetail.city;
    _address=result.address;
}

}

/* 定位失败后,会调用次函数 */ -(void)didFailToLocateUserWithError:(NSError )error{ [self stopLocation]; }

三、一个完成的单例模式,百度地图的实现基本就就这样了。看起来是不是 so easy!

__如有不完善的欢迎大家批评指正。

收藏
0
sina weixin mail 回到顶部