在项目功能中有一个定位CLLocation的需求,遇到了一些知识难点,经过各位大侠的帮助,问题解决,特此分享供大家学习,希望大家共同学习进步。
一、简单说明
1.CLLocationManager
CLLocationManager的常用操作和属性
开始用户定位- (void)startUpdatingLocation;
停止用户定位- (void) stopUpdatingLocation;
说明:当调用了startUpdatingLocation方法后,就开始不断地定位用户的位置,中途会频繁地调用代理的下面方法
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations;
每隔多少米定位一次
@property(assign, nonatomic) CLLocationDistance distanceFilter;
定位精确度(越精确就越耗电)
@property(assign, nonatomic) CLLocationAccuracy desiredAccuracy;
使用定位功能,首先要导入框架,遵守CLLocationManagerDelegate协议,再创建位置管理器CLLocationManager
在iOS8.0后,定位功能需要在info.plist中加入NSLocationWhenInUseUsageDescription和NSLocationAlwaysUsageDescription这两个NSString类型字段,才能够使用定位功能
代码贴出来与大家共勉,各位看官自行研究
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
{ self.locationManager = [[CLLocationManager alloc] init]; _locationManager.delegate = self; if ([CLLocationManager locationServicesEnabled] == NO) { // NSLog(@"没有GPS服务"); } //地理位置精确度 _locationManager.desiredAccuracy=kCLLocationAccuracyNearestTenMeters; //设置距离筛选器,double类型,只要距离变化多少,就调用委托代理 self.locationManager.distanceFilter = kCLDistanceFilterNone; // meters [_locationManager requestWhenInUseAuthorization]; // 前台定位 [_locationManager startUpdatingLocation]; } - ( void )locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations { NSLog(@ "longitude = %f" , ((CLLocation *)[locations lastObject]).coordinate.longitude); NSLog(@ "latitude = %f" , ((CLLocation *)[locations lastObject]).coordinate.latitude); CGFloat longTI=((CLLocation *)[locations lastObject]).coordinate.longitude; CGFloat latTI=((CLLocation *)[locations lastObject]).coordinate.latitude; //将经度显示到label上 _longitudeLabel.text = [NSString stringWithFormat:@ "%f" ,longTI]; //将纬度现实到label上 _latitudeLabel.text = [NSString stringWithFormat:@ "%f" ,latTI]; // 获取当前所在的城市名 CLGeocoder *geocoder = [[CLGeocoder alloc] init]; //根据经纬度反向地理编译出地址信息 [geocoder reverseGeocodeLocation:locations.lastObject completionHandler:^(NSArray *array, NSError *error) { if (array.count > 0 ) { CLPlacemark *placemark = [array objectAtIndex: 0 ]; // //将获得的所有信息显示到label上 // self.location.text = placemark.name; //获取城市 NSString *city = placemark.locality; if (!city) { //四大直辖市的城市信息无法通过locality获得,只能通过获取省份的方法来获得(如果city为空,则可知为直辖市) city = placemark.administrativeArea; } // NSLog(@"city = %@", city); _cityName=city; } else if (error == nil && [array count] == 0 ) { // NSLog(@"No results were returned."); } else if (error != nil) { // NSLog(@"An error occurred = %@", error); } }]; //系统会一直更新数据,直到选择停止更新,因为我们只需要获得一次经纬度即可,所以获取之后就停止更新 [manager stopUpdatingLocation]; } |
以上是关于服务器之家小编给大家整理的IOS开发之详解定位CLLocation,后续还会持续更新,希望大家能够喜欢。