</pre><p>现在的物流APP,团购App很多都需要使用到定位功能,怎么才能用最少的时间与精力搞定定位功能呢,其实我也没有什么经验,只是把我的demo分享一下,系统自带的<span style="color: rgb(228, 68, 72); font-family: Menlo; font-size: 11px;"><CoreLocation/CoreLocation.h>帮助我们不少,当然,之前还需导入</span></p><p style="margin-top: 0px; margin-bottom: 0px; font-size: 11px; line-height: normal; font-family: Menlo; color: rgb(228, 68, 72);"><span style="font-variant-ligatures: no-common-ligatures; color: #d28f5a">#import </span><span style="font-variant-ligatures: no-common-ligatures"><MapKit/MapKit.h></span></p><p><pre name="code" class="objc">@implementation ViewController
- (CLLocationManager *)mgr {
//创建位置管理者(定位用户的位置)
if (!_mgr) {
_mgr = [[CLLocationManager alloc]init];
_mgr.delegate = self;
}
return _mgr;
}
/**
CLLocationManager 的基本使用
*/
- (void)viewDidLoad {
[super viewDidLoad];
//定位初始化(IOS 8开始要正常使用定位功能必须请求定位授权,这点是非常重要的,执行到这来后就会弹出那个允许定位的框框)
if ([CLLocationManager locationServicesEnabled]) {
[self.mgr requestWhenInUseAuthorization];
self.mgr.desiredAccuracy = kCLLocationAccuracyBest;
self.mgr.distanceFilter = kCLLocationAccuracyBest;
[self.mgr startUpdatingLocation];
//监控location区域的改变
//[self.mgr startMonitoringForRegion:<#(nonnull CLRegion *)#>];
}else{
// 1.告诉用户检查网络状况
// 2.提醒用户打开定位开关
}
}
//计算两个位置之间的距离
- (void)couontDistance {
CLLocation *loc1 = [[CLLocation alloc]initWithLatitude:40 longitude:116];
CLLocation *loc2 = [[CLLocation alloc]initWithLatitude:40 longitude:118];
CLLocationDistance dest = [loc1 distanceFromLocation:loc2];
NSLog(@"(%@)和(%@)的距离:%f",loc1,loc2,dest);
}
#pragma locationManagerDelegate
/**
* 当定位到用户的位置时,就会调用(调用比较频繁)
*/
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
// NSLog(@"didUpdateLocations--%d",locations.count);
// 数组里面存放的是CLLocation对象, 一个CLLocation就代表一个位置
CLLocation *loc = [locations lastObject];
NSLog(@"latitude:%f longtitude:%f",loc.coordinate.longitude,loc.coordinate.latitude);
// 停止更新位置(不用定位服务,应当马上停止定位,非常耗电)
[self.mgr stopUpdatingLocation];
}
//进入区域
- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region {
}
//退出这个区域的时候调用
- (void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region {
}