地图定位
CLLocationManager *locationManager = [[CLLocationManager alloc]init];
locationManager.delegate = self;
设置精确度
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = 10;
[locationManager requestAlwaysAuthorization];
[locationManager startUpdatingLocation];
遵循的代理:CLLocationManagerDelegate
实现的方法:
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
CLLocation *location = [locations objectAtIndex:0];
通过位置对象,获取带有用户经纬度的结构体
CLLocationCoordinate2D lc2d =location.coordinate;
获取经纬度
CLLocationDegrees lat = lc2d.latitude;纬度
CLLocationDegrees longt = lc2d.longitude; 经度
NSLog(@"纬度:%f 经度:%f",lat,longt);
CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
[geoCoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
for (CLPlacemark * placemark in placemarks) {
NSDictionary *test = [placemark addressDictionary];
Country(国家) State(城市) SubLocality(区)
NSLog(@"%@", [test objectForKey:@"State"]);
self.stateString = [[test objectForKey:@"State"] substringWithRange:NSMakeRange(0, [[test objectForKey:@"State"] length] - 1)];
NSLog(@"%@",self.stateString);
UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:self.stateString style:UIBarButtonItemStyleDone target:self action:@selector(clickRightButton)];
self.navigationItem.rightBarButtonItem = rightButton;
NSLog(@"error:%@",error.localizedDescription);
}
}];
}
当用户拒绝程序访问gps功能,或者定位失败时,调用此方法
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithTitle:@"城市" style:UIBarButtonItemStyleDone target:self action:@selector(clickRightButton)];
self.navigationItem.rightBarButtonItem = rightButton;
NSLog(@"error:%@",error.localizedDescription);
}