最近公司有点业务需求的变化,要我负责地图的相关开发,苦苦找了很多资料,今天准备整理整理一下定位相关的方法。
苹果自己有的定位的库,CoreLocation.使用corelocation定位很简单,就是创建管理者对象,让管理者的对象的代理=self,调用
startUpdatingLocation方法就可以实现定位的方法。废话不多说,直接看下面的代码:
#import "TXBMapKitController.h"
#import <CoreLocation/CoreLocation.h>
@interface TXBMapKitController ()<CLLocationManagerDelegate>
//引用管理者
@property (nonatomic, strong) CLLocationManager *locationManage;
@end
@implementation TXBMapKitController
//懒加载
- (CLLocationManager *)locationManage{
if (!_locationManage) {
_locationManage = [[CLLocationManager alloc] init];
_locationManage.delegate = self;
}
return _locationManage;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
if ([CLLocationManager locationServicesEnabled] == NO) {
return;
}
[self.locationManage startUpdatingLocation];
//测试位置距离
[self distanceTest];
}
- (void)distanceTest{
CLLocation *loc1 = [[CLLocation alloc] initWithLatitude:40.0 longitude:117.0];
CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:41.0 longitude:117.0];
CLLocationDistance distance = [loc1 distanceFromLocation:loc2];
NSLog(@"%f",distance);
}
#pragma mark -- CLLocationManagerDelegate
//这个方法调用非常频繁,慎用
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
for (CLLocation *location in locations) {
CLLocationDegrees latitude = location.coordinate.latitude;
CLLocationDegrees longtitude = location.coordinate.longitude;
NSLog(@"纬度:%f,经度:%f",latitude,longtitude);
}
// [self.locationManage stopUpdatingLocation];
}
@end
这里面有几个数据结构一定要搞清楚,CoreLocation对象里面有Coordinate(结构体,含有纬度和经度)属性,可以从这里面获取精确的位置。
代理方法
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations必须是在管理者调用了<p style="margin-top: 0px; margin-bottom: 0px; font-size: 14px; font-family: Menlo;">startUpdatingLocation后才会在位置变化后调用,并且调用的频率非常高。一般情况下谨慎使用。</p>