地图用到的地方挺多的, 每个项目都会获取当前用户的当前的使用位置. 就顺便封装了下地图的使用, 以便下次使用.
首先我们需要先定义几个宏, 这样我们在获取一些数据的时候, 就可以直接拿出来使用, 不用再保存成对象.
需要定义的宏
#define kCityTitle @"city"
#define kProvinceTitle @"province"
#define kCityNoTitle @"cityNo"
#define kCityNameTitle @"cityName"
我们需要创建两个类, 一个类用来初始化对象.
我们先创建 MMLocationManager
对象, 用来实例化定位对象
创建的MMLocationManager.h
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
typedef void (^LocationSuccessBlock)(void);
typedef void (^LocationErrorBlock)(void);
@interface MMLocationManager : NSObject<CLLocationManagerDelegate>
@property (nonatomic, retain) CLLocationManager *locationManager;
/**
* 定位实例对象
* @return
* @date 2015-03-10
* @author victor
*/
+ (MMLocationManager *)shareLocation;
/**
* 开始定位
* @date 2015-03-10
* @author victor
*/
- (void)startLocation;
/**
* 获取定位状态
* @pram successBlock 成功
* @pram errorBlock 失败
* @date 2015-05-04
* @author victor
*/
- (void)locationStatusWithSuccess:(LocationSuccessBlock)successBlock withError:(LocationErrorBlock)errorBlock;
@end
创建的MMLocationManager.m
#import "MMLocationManager.h"
static MMLocationManager *_sharedObject = nil;
@interface MMLocationManager ()
@property (nonatomic, strong) LocationSuccessBlock successBlock;
@property (nonatomic, strong) LocationErrorBlock errorBlock;
@end
@implementation MMLocationManager
@synthesize locationManager;
/**
* 定位实例对象
* @return
* @date 2015-03-10
* @author victor
*/
+ (MMLocationManager *)shareLocation;
{
@synchronized(self){
if (_sharedObject == nil) {
_sharedObject = [[self alloc] init];
}
}
return _sharedObject;
}
- (id)init {
self = [super init];
if (self) {
// example
// 实例化一个位置管理器
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
// 设置定位精度
// kCLLocationAccuracyNearestTenMeters:精度10米
// kCLLocationAccuracyHundredMeters:精度100 米
// kCLLocationAccuracyKilometer:精度1000 米
// kCLLocationAccuracyThreeKilometers:精度3000米
// kCLLocationAccuracyBest:设备使用电池供电时候最高的精度
// kCLLocationAccuracyBestForNavigation:导航情况下最高精度,一般要有外接电源时才能使用
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
// distanceFilter是距离过滤器,为了减少对定位装置的轮询次数,位置的改变不会每次都去通知委托,而是在移动了足够的距离时才通知委托程序
// 它的单位是米,这里设置为至少移动1000再通知委托处理更新;
self.locationManager.distanceFilter = 1000.0f; // 如果设为kCLDistanceFilterNone,则每秒更新一次;
/* 开始定位 */
//[self startLocation];
}
return self;
}
/**
* 开始定位
* @date 2015-03-10
* @author victor
*/
-(void)startLocation
{
// 判断的手机的定位功能是否开启
// 开启定位:设置 > 隐私 > 位置 > 定位服务
// 启动位置更新
// 开启位置更新需要与服务器进行轮询所以会比较耗电,在不需要时用stopUpdatingLocation方法关闭;
if([CLLocationManager locationServicesEnabled]){
//如果是8.0以上的系统
if ([NSString phoneMaxVersion].floatValue > 8.0) {
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways
|| [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined ||[CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse) {
[locationManager requestAlwaysAuthorization];
[self.locationManager requestWhenInUseAuthorization];
[self.locationManager startUpdatingLocation];
}else if([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied){
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"请打开定位服务"
message:@"请在\"设置\"->\"隐私\"->\"位置\"->\"定位服务\"中开启\"易民通\"的定位权限"
delegate:nil
cancelButtonTitle:@"确定"
otherButtonTitles:nil, nil];
[alert show];
}
}else{
//8.0以下的系统
if (([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorized
|| [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined)) {
[self.locationManager startUpdatingLocation];
}else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied){
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"请打开定位服务"
message:@"请在\"设置\"->\"隐私\"->\"位置\"->\"定位服务\"中开启\"易民通\"的定位权限"
delegate:self
cancelButtonTitle:@"确定"
otherButtonTitles:nil, nil];
[alert show];
}
}
}else{
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"请打开定位服务"
message:@"请在\"设置\"->\"隐私\"->\"位置\"->\"定位服务\"中开启\"易民通\"的定位权限"
delegate:nil
cancelButtonTitle:@"确定"
otherButtonTitles:nil, nil];
[alert show];
}
}
/**
* 定位更新状态
* @date 2015-04-07
* @author victor
*/
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation * currLocation = [locations lastObject];
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
CLLocationCoordinate2D myCoOrdinate;
myCoOrdinate.latitude = currLocation.coordinate.latitude;
myCoOrdinate.longitude = currLocation.coordinate.longitude;
CLLocation *location = [[CLLocation alloc] initWithLatitude:myCoOrdinate.latitude longitude:myCoOrdinate.longitude];
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error){
if (error){
NSLog(@"failed with error: %@", error);
return;
}
if(placemarks.count > 0){
CLPlacemark *placemark = (CLPlacemark*)[placemarks objectAtIndex:0];
NSString *strProvince = placemark.administrativeArea;
NSString *strCity = placemark.locality;
/* 保存获取到的省市数据 */
[LYUserDefaults setObject:strProvince forKey:kProvinceTitle];
[LYUserDefaults setObject:strCity forKey:kCityTitle];
[LYUserDefaults synchronize];
if (_successBlock) {
_successBlock ();
_successBlock = nil;
}
}
}];
/* 停止位置更新 */
[manager stopUpdatingLocation];
}
/**
* 定位当前位置失败
* @pram manager
* @pram error
* @date 2015-04-30
* @author victor
*/
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
if (_errorBlock) {
_errorBlock ();
_errorBlock = nil;
}
}
/**
* 获取定位状态
* @pram successBlock 成功
* @pram errorBlock 失败
* @date 2015-05-04
* @author victor
*/
- (void)locationStatusWithSuccess:(LocationSuccessBlock)successBlock withError:(LocationErrorBlock)errorBlock;
{
self.successBlock = successBlock;
self.errorBlock = errorBlock;
}
@end
创建另一个对象,用来获取用户的位置信息
创建LocationManager
对象
LocationManager.h
#import <Foundation/Foundation.h>
@interface LocationManager : NSObject
/**
* 判断当前定位是否开启
* @return YES & NO
* @date 2015-03-16
* @author victor
*/
+ (BOOL)isOpenLocation;
/**
* 获取当前城市编号
* @return
* @date 2015-03-20
* @author victor
*/
+ (NSString *)getCurrentCityNo;
/**
* 获取城市列表数据
* @return
* @date 2015-03-16
* @author victor
*/
+ (NSArray *)getCityList;
/**
* 获取城市编号
* @return cityNo
* @date 2015-03-16
* @author victor
*/
+ (NSString *)getWithCityName:(NSString *)city;
/**
* 获取当前定位城市
* @return
* @date 2015-03-16
* @author victor
*/
+ (NSString *)getCurrentCity;
@end
LocationManager.m
#import "LocationManager.h"
#import <CoreLocation/CoreLocation.h>
@implementation LocationManager
/**
* 判断当前定位是否开启
* @return YES & NO
* @date 2015-03-16
* @author victor
*/
+ (BOOL)isOpenLocation{
if(![CLLocationManager locationServicesEnabled] || ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusDenied)) {
return NO;
}
return YES;
}
/**
* 获取当前城市编号
* @pram cityName 城市名称
* @return
* @date 2015-03-20
* @author victor
*/
+ (NSString *)getCurrentCityNo
{
__block NSString *cityNo = nil;
NSString *strProvince = [LYUserDefaults objectForKey:kProvinceTitle];
NSString *strCity = [LYUserDefaults objectForKey:kCityTitle];
if ([NSString phoneMaxVersion].floatValue > 8) {
if ([strProvince isEqualToString:@"北京市"] || [strProvince isEqualToString:@"上海市"] || [strProvince isEqualToString:@"天津市"] || [strProvince isEqualToString:@"重庆市"]) {
[[self getCityList] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([[obj objectForKey:kCityNameTitle] isEqualToString:strProvince]) {
*stop = YES;
cityNo = [obj objectForKey :kCityNoTitle];
}
}];
if (cityNo.length > 0) {
return cityNo;
}else{
return @"9999";
}
}else{
[[self getCityList] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([[obj objectForKey:kCityNameTitle] isEqualToString:strCity]) {
*stop = YES;
cityNo = [obj objectForKey:kCityNoTitle];
}
}];
if (cityNo.length > 0) {
return cityNo;
}else{
return @"9999";
}
}
}else{
if ([strCity length] < 1 || [strCity isEqualToString:@"null"]) {
[[self getCityList] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([[obj objectForKey:kCityNameTitle] isEqualToString:strProvince]) {
*stop = YES;
cityNo = [obj objectForKey:kCityNoTitle];
}
}];
if (cityNo.length > 0) {
return cityNo;
}else{
return @"9999";
}
}else{
if ([strProvince isEqualToString:@"北京市"] || [strProvince isEqualToString:@"上海市"] || [strProvince isEqualToString:@"天津市"] || [strProvince isEqualToString:@"重庆市"]) {
[[self getCityList] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([[obj objectForKey:kCityNameTitle] isEqualToString:strProvince]) {
*stop = YES;
cityNo = [obj objectForKey :kCityNoTitle];
}
}];
if (cityNo.length > 0) {
return cityNo;
}else{
return @"9999";
}
}else{
[[self getCityList] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([[obj objectForKey:kCityNameTitle] isEqualToString:strCity]) {
*stop = YES;
cityNo = [obj objectForKey:kCityNoTitle];
}
}];
if (cityNo.length > 0) {
return cityNo;
}else{
return @"9999";
}
}
}
}
}
/**
* 获取城市列表数据
* @return
* @date 2015-03-16
* @author victor
*/
+ (NSArray *)getCityList
{
return [NSMutableArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:kCityTitle ofType:@"plist"]];
}
/**
* 获取城市编号
* @return cityNo
* @date 2015-03-16
* @author victor
*/
+ (NSString *)getWithCityName:(NSString *)city
{
__block NSString *cityNo = nil;
[[self getCityList] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([[obj objectForKey:kCityNameTitle] isEqualToString:city]) {
*stop = YES;
cityNo = [obj objectForKey:kCityNoTitle];
}
}];
return cityNo;
}
/**
* 获取当前定位城市
* @return
* @date 2015-03-16
* @author victor
*/
+ (NSString *)getCurrentCity
{
NSString *city = nil;
NSString *currentProvince = [LYUserDefaults objectForKey:kProvinceTitle];
NSString *currentCity = [LYUserDefaults objectForKey:kCityTitle];
if ([currentProvince isEqualToString:@"北京市"] || [currentProvince isEqualToString:@"上海市"] || [currentProvince isEqualToString:@"天津市"] || [currentProvince isEqualToString:@"重庆市"])
{
city = currentProvince;
}else{
city = currentCity;
}
return city;
}
@end
我们在使用的时候, 需要先实例化定位对象, 然后在获取定位对象
在使用LocationManager
对象, 获取用户当前位置信息
使用方法
/* 获取定位服务 */
[[MMLocationManager shareLocation] startLocation];
[[MMLocationManager shareLocation] locationStatusWithSuccess:^{
MyLog(@"当前城市名称%@",[LocationManager getCurrentCity]);
MyLog(@"获取当前城市编号%@",[LocationManager getCurrentCityNo]);
MyLog(@"获取城市编号%@",[LocationManager getWithCityName:[LocationManager getCurrentCity]]);
} withError:^{
MyLog(@"定位状态不可用"
}];
2016-11-03 09:51:48.142 yimintong[7203:60b] 当前城市名称北京市
2016-11-03 09:51:48.147 yimintong[7203:60b] 获取当前城市编号1101
2016-11-03 09:51:48.152 yimintong[7203:60b] 获取城市编号1101
网友评论