IOS开发笔记整理49之详解定位CLLocation
在项目功能中有一个定位CLLocation的需求,遇到了一些知识难点,经过各位大侠的帮助,问题解决,特此分享供大家学习,希望大家共同学习进步。
一、简单说明
1.CLLocationManager
CLLocationManager的常用操作和属性
开始用户定位-(void)startUpdatingLocation;
停止用户定位-(void)stopUpdatingLocation;
说明:当调用了startUpdatingLocation方法后,就开始不断地定位用户的位置,中途会频繁地调用代理的下面方法
-(void)locationManager:(CLLocationManager*)managerdidUpdateLocations:(NSArray*)locations;
每隔多少米定位一次
@property(assign,nonatomic)CLLocationDistancedistanceFilter;
定位精确度(越精确就越耗电)
@property(assign,nonatomic)CLLocationAccuracydesiredAccuracy;
使用定位功能,首先要导入框架,遵守CLLocationManagerDelegate协议,再创建位置管理器CLLocationManager
在iOS8.0后,定位功能需要在info.plist中加入NSLocationWhenInUseUsageDescription和NSLocationAlwaysUsageDescription这两个NSString类型字段,才能够使用定位功能
代码贴出来与大家共勉,各位看官自行研究
{
self.locationManager=[[CLLocationManageralloc]init];
_locationManager.delegate=self;
if([CLLocationManagerlocationServicesEnabled]==NO){
//NSLog(@"没有GPS服务");
}
//地理位置精确度
_locationManager.desiredAccuracy=kCLLocationAccuracyNearestTenMeters;
//设置距离筛选器,double类型,只要距离变化多少,就调用委托代理
self.locationManager.distanceFilter=kCLDistanceFilterNone;//meters
[_locationManagerrequestWhenInUseAuthorization];//前台定位
[_locationManagerstartUpdatingLocation];
}
-(void)locationManager:(CLLocationManager*)manager
didUpdateLocations:(NSArray*)locations
{
NSLog(@"longitude=%f",((CLLocation*)[locations
lastObject]).coordinate.longitude);
NSLog(@"latitude=%f",((CLLocation*)[locationslastObject]).coordinate.latitude);
CGFloatlongTI=((CLLocation*)[locations
lastObject]).coordinate.longitude;
CGFloatlatTI=((CLLocation*)[locationslastObject]).coordinate.latitude;
//将经度显示到label上
_longitudeLabel.text=[NSStringstringWithFormat:@"%f",longTI];
//将纬度现实到label上
_latitudeLabel.text=[NSStringstringWithFormat:@"%f",latTI];
//获取当前所在的城市名
CLGeocoder*geocoder=[[CLGeocoderalloc]init];
//根据经纬度反向地理编译出地址信息
[geocoderreverseGeocodeLocation:locations.lastObjectcompletionHandler:^(NSArray*array,NSError*error)
{
if(array.count>0)
{
CLPlacemark*placemark=[arrayobjectAtIndex:0];
////将获得的所有信息显示到label上
//self.location.text=placemark.name;
//获取城市
NSString*city=placemark.locality;
if(!city){
//四大直辖市的城市信息无法通过locality获得,只能通过获取省份的方法来获得(如果city为空,则可知为直辖市)
city=placemark.administrativeArea;
}
//NSLog(@"city=%@",city);
_cityName=city;
}
elseif(error==nil&&[arraycount]==0)
{
//NSLog(@"Noresultswerereturned.");
}
elseif(error!=nil)
{
//NSLog(@"Anerroroccurred=%@",error);
}
}];
//系统会一直更新数据,直到选择停止更新,因为我们只需要获得一次经纬度即可,所以获取之后就停止更新
[managerstopUpdatingLocation];
}
以上是关于毛票票小编给大家整理的IOS开发之详解定位CLLocation,后续还会持续更新,希望大家能够喜欢。