博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
GPS定位的实现
阅读量:4622 次
发布时间:2019-06-09

本文共 6883 字,大约阅读时间需要 22 分钟。

1、定义一个GPS管理类:

GPSLocationManager.h:

#import 
#import "SingletonTemplate.h"// GPS定位#import
#import
@interface GPSLocationManager : NSObject
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 GPSLocationManagersingleton_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

你可能感兴趣的文章
死磕 java同步系列之AQS起篇
查看>>
利用Lucene把文本的字体格式进行改动,然后输出到一个新的文件里
查看>>
[Openstack] Expecting an auth URL via either --os-auth-url or env[OS_AUTH_URL]
查看>>
How to Create Modifiers Using the API QP_MODIFIERS_PUB.PROCESS_MODIFIERS
查看>>
待飞笔记(第一天 )
查看>>
解惑好文:移动端H5页面高清多屏适配方案
查看>>
traefik添加多证书
查看>>
PhantomJs 笔记
查看>>
js设计模式--语言类型
查看>>
C#多线程之二:ManualResetEvent和AutoResetEvent
查看>>
忽略UserInterfaceState.xcuserstate
查看>>
ReactNative--Flexbox布局
查看>>
java实现读取文件大全
查看>>
[Cordova] 无法显示Alert视窗
查看>>
借助过度区选择阈值
查看>>
评论列表显示及排序,个人中心显示
查看>>
JavaWeb学习笔记总结 目录篇
查看>>
C#根据html生成PDF
查看>>
Neutron SDN 手动实现手册
查看>>
linux下core文件调试方法
查看>>