ios使用系统定位在ios8.0之后需要在info.plist添加NSLocationAlwaysUsageDescription与NSLocationWhenInUseUsageDescription两个key
- (void)viewDidLoad {
[superviewDidLoad];
self.view.backgroundColor = [UIColorgrayColor];
locationManager = [[CLLocationManageralloc]init];
//设置代理
locationManager.delegate =self;
//设置定位精度
locationManager.desiredAccuracy =kCLLocationAccuracyBest;
//定位频率,每隔多少米定位一次
CLLocationDistance distance =10.0;//十米定位一次
locationManager.distanceFilter = distance;
//启动跟踪定位
[locationManagerstartUpdatingLocation];
if ([CLLocationManagerauthorizationStatus] == kCLAuthorizationStatusNotDetermined){
if ([[UIDevicecurrentDevice].systemVersionfloatValue] >= 8.0) {
[locationManagerrequestWhenInUseAuthorization];
[locationManagerrequestAlwaysAuthorization];
}
}
if ([CLLocationManagerauthorizationStatus] == kCLAuthorizationStatusDenied) {//用户选择永不使用定位需要进行提示
if ([[UIDevicecurrentDevice].systemVersionfloatValue] >= 9.0){
[selfperformSelector:@selector(delayMethod)withObject:nilafterDelay:1.0];//延迟执行,否则未加载完毕viewController无法弹出报错
}
else{
UIAlertView * al = [[UIAlertViewalloc]initWithTitle:@"提示"message:@"你没有授权"delegate:selfcancelButtonTitle:@"确定"otherButtonTitles: nil];
[al show];
}
}
}
-(void)delayMethod
{
UIAlertController * alertController = [UIAlertControlleralertControllerWithTitle:@"提示"message:@"你没有授权"preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertActionactionWithTitle:@"确定"style:UIAlertActionStyleCancelhandler:nil];
[alertControlleraddAction:cancelAction];
[selfpresentViewController:alertControlleranimated:YEScompletion:nil];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
CLLocation *location=[locationsfirstObject];//取出第一个位置
CLLocationCoordinate2D coordinate=location.coordinate;//位置坐标
NSLog(@"经度:%f,纬度:%f,海拔:%f,航向:%f,行走速度:%f",coordinate.longitude,coordinate.latitude,location.altitude,location.course,location.speed);
//如果不需要实时定位,使用完即使关闭定位服务
[locationManagerstopUpdatingLocation];
_geocoder=[[CLGeocoderalloc]init];
[selfgetCoordinateByAddress:@"上海"];
[selfgetAddressByLatitude:coordinate.latitudelongitude:coordinate.longitude];
}
-(void)getCoordinateByAddress:(NSString *)address{
//地理编码
[_geocodergeocodeAddressString:address completionHandler:^(NSArray *placemarks,NSError *error) {
//取得第一个地标,地标中存储了详细的地址信息,注意:一个地名可能搜索出多个地址
CLPlacemark *placemark=[placemarksfirstObject];
NSLog(@"详细信息:%@",placemark);
}];
}
-(void)getAddressByLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude{
//反地理编码
CLLocation *location=[[CLLocationalloc]initWithLatitude:latitudelongitude:longitude];
[_geocoderreverseGeocodeLocation:location completionHandler:^(NSArray *placemarks,NSError *error) {
CLPlacemark *placemark=[placemarksfirstObject];
NSLog(@"详细信息:%@",placemark);
}];
}