GPS定位的实现

1、定义一个GPS管理类:

GPSLocationManager.h:

#import <Foundation/Foundation.h>
#import "SingletonTemplate.h"

// GPS定位
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>

@interface GPSLocationManager : NSObject <CLLocationManagerDelegate>

singleton_for_header(GPSLocationManager)


#pragma mark - GPS定位成功与失败的回调block
/**
 *  GPS 定位成功与失败的block
 */
@property (nonatomic, copy) void (^gpsSuccessBlock)(CLLocationDistance longitude, CLLocationDistance latitude);
@property (nonatomic, copy) void (^gpsFailureBlock)();

- (void)addGpsSuccessCallback:(void (^)(CLLocationDistance longitude, CLLocationDistance latitude))callback;
- (void)addGpsFailureCallback:(void (^)())callback;

#pragma mark - 开启/停止 GPS定位
/**
 *  开启GPS定位
 *  停止GPS定位
 */
- (void)startGPSLocation;
- (void)stopGPSLocation;


#pragma mark - 通过经纬度坐标获取当前地理位置
/**
 *  通过经纬度坐标获取当前地理位置
 *
 *  @param longitude 经度
 *  @param latitude  纬度
 */
- (void)gpsLocationInfoByLong:(CLLocationDistance)longitude
                          lat:(CLLocationDistance)latitude
                 locationInfo:(void (^)(CLPlacemark *gpsInfo))info;

@end

GPSLocationManager.m文件内容:

#import "GPSLocationManager.h"
#import "MHLocationConverter.h"

@interface GPSLocationManager ()

@property (strong, nonatomic) CLLocationManager *locationManager;   // 定位管理器
@property (assign, nonatomic) CLLocationDistance longitude;         // 经度
@property (assign, nonatomic) CLLocationDistance latitude;          // 纬度
@property (strong, nonatomic) CLGeocoder *geocoder;                 // 位置反编译

@end

@implementation GPSLocationManager

singleton_for_class(GPSLocationManager)


#pragma mark - 开启GPS定位
- (void)startGPSLocation
{
    // 检查是否开启了定位服务
    if (![CLLocationManager locationServicesEnabled])
    {
        // 定位不可用
        DEF_DEBUG(@"定位服务没有开启");
        
        return;
    }
    
    self.locationManager = [[CLLocationManager alloc] init];
    
    // 判斷是否 iOS 8
    if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
        //        [self.locationManager requestAlwaysAuthorization];      // 永久授权
        [self.locationManager requestWhenInUseAuthorization];   //使用中授权
    }
    
    self.locationManager.delegate = self;
    
    // 所需的位置精度
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    
    // 指定用米的最小距离更新
    self.locationManager.distanceFilter = kCLDistanceFilterNone;
    
    // 开始定位
    [self.locationManager startUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    DEF_DEBUG(@"设备旋转指向:%u",status);
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    DEF_DEBUG(@"定位失败:%@",error);
    
    // GPS 定位失败
    if (self.gpsFailureBlock)
    {
        self.gpsFailureBlock();
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    // WGS-84坐标转为BD-09坐标
    CLLocationCoordinate2D coord = [MHLocationConverter wgs84ToBd09:newLocation.coordinate];
    
    DEF_DEBUG(@"GPS 定位转换为百度地图用的经度:%f, 纬度:%f", coord.longitude, coord.latitude);
    
    // 得到转换后的经纬度
    self.longitude  = coord.longitude;
    self.latitude   = coord.latitude;
    
    // GPS 定位成功
    if (self.gpsSuccessBlock)
    {
        self.gpsSuccessBlock(self.longitude, self.latitude);
    }
}

#pragma mark - 停止定位
- (void)stopGPSLocation
{
    [self.locationManager stopUpdatingLocation];
}


#pragma mark - 通过经纬度坐标获取当前地理位置
- (void)gpsLocationInfoByLong:(CLLocationDistance)longitude
                          lat:(CLLocationDistance)latitude
                 locationInfo:(void (^)(CLPlacemark *gpsInfo))info
{
    /**
     *  反编译经纬度
     */
    
    // 传入的坐标系是BD-09的
    CLLocationCoordinate2D coord;
    coord.longitude = longitude;
    coord.latitude  = latitude;
    
    // 从BD-09坐标转回到GCJ-02,再进行位置转化
    CLLocationCoordinate2D newCoord = [MHLocationConverter bd09ToGcj02:coord];
    
    // 防止循环引用
    __unsafe_unretained typeof(self) _self  = self;
    
    _self.geocoder = [[CLGeocoder alloc] init];
    [_self.geocoder reverseGeocodeLocation:[[CLLocation alloc] initWithLatitude:newCoord.latitude longitude:newCoord.longitude]
                         completionHandler:^(NSArray *placemarks, NSError *error) {
                             
                             // 当前位置的数据信息
                             if (error == nil && placemarks.count > 0)
                             {
                                 CLPlacemark *placemark = [placemarks objectAtIndex:0];
                                 
                                 DEF_DEBUG(@"定位结果: %@", placemark);
                                 
                                 // block回调
                                 if (info)
                                 {
                                     info(placemark);
                                 }
                             }
                             else if (error == nil && placemarks.count == 0)
                             {
                                 DEF_DEBUG(@"经纬度逆编译没有结果返回");
                             }
                             else if (error != nil)
                             {
                                 DEF_DEBUG(@"经纬度逆编译错误: %@", error);
                             }
                         }];
}



#pragma mark - block
- (void)addGpsSuccessCallback:(void (^)(CLLocationDistance longitude, CLLocationDistance latitude))callback
{
    self.gpsSuccessBlock = callback;
}

- (void)addGpsFailureCallback:(void (^)())callback
{
    self.gpsFailureBlock = callback;
}


@end

2、在AppDelegate里面实现 gpsLocate方法,开启定位

#pragma mark - GPS定位
- (void)gpsLocate
{
    // 防止循环引用
    __unsafe_unretained typeof([GPSLocationManager sharedGPSLocationManager]) gps = [GPSLocationManager sharedGPSLocationManager];
    
    // 开启定位
    [gps startGPSLocation];
    
    // 定位结果
    gps.gpsFailureBlock = ^(){
        // 定位失败
    };
    
    gps.gpsSuccessBlock = ^(CLLocationDistance longitude, CLLocationDistance latitude){
        
        // 停止定位
        [gps stopGPSLocation];
        
        // 定位成功
        
        NSLog(@"定位成功,经度:%f, 纬度:%f", longitude, latitude);
        
        // 逆编译地区
        [gps gpsLocationInfoByLong:longitude lat:latitude locationInfo:^(CLPlacemark *gpsInfo) {
            //
            NSLog(@"写法一,当前地理位置信息: %@", gpsInfo);
            
            // 获取城市
            NSString *city = gpsInfo.locality;
            if (!city)
            {
                
                // 四大直辖市的城市信息无法通过locality获得,只能通过获取省份的方法来获得(如果city为空,则可知为直辖市)
                city = gpsInfo.administrativeArea;
            }
            
            NSLog(@"city = %@", city);
            
            NSMutableString *mutable = [[NSMutableString alloc] initWithString:city];
            
            if ([mutable rangeOfString:@"市辖区"].location != NSNotFound)
            {
                [mutable deleteCharactersInRange:NSMakeRange([mutable length]-3, 3)];
                city = mutable;
            }
        }];
    };
}
原文地址:https://www.cnblogs.com/angongIT/p/5333162.html