在项目中要用到定位所在地的功能,这里大致说下我的做法:
首先要使用定位,需要在所在的类#import <MapKit/MapKit.h> ,然后继承协议CLLocationManagerDelegate,在.h类定义CLLocationManager* _locationManager;
CLGeocoder* _currentCityGeocoder;
在.m类中实现:
_currentCityGeocoder = [[CLGeocoder alloc] init];
_locationManager = [[CLLocationManager alloc] init];
_locationManager.delegate = self;
_locationManager.distanceFilter = 1000.0f;//用来控制定位服务更新频率。单位是“米”
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;//这个属性用来控制定位精度,精度越高耗电量越大。
[_locationManager startUpdatingLocation];
然后实现代理方法:
#pragma mark - mapDelegate
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
[_locationManager stopUpdatingLocation];
NSString *strLat = [NSString stringWithFormat:@"%.4f",newLocation.coordinate.latitude];
NSString *strLng = [NSString stringWithFormat:@"%.4f",newLocation.coordinate.longitude];
NSLog(@"Lat: %@ Lng: %@", strLat, strLng);
[_currentCityGeocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark* placeMark = [placemarks objectAtIndex:0];
NSString* currentCityStr = [placeMark locality];
NSLog(@"当前省份为:%@",placeMark.administrativeArea);
NSLog(@"当前城市为:%@",currentCityStr);
_currentLocationLabel.text = [placeMark.administrativeArea stringByAppendingFormat:@" %@",currentCityStr];
[self.progress dismiss];
// _locationLabel.text = placeMark.administrativeArea;
// we have received our current location, so enable the "Get Current Address" button
}];
}
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error
{
// Failed to receive user's location
NSString *errorMsg = nil;
if ([error code] == kCLErrorDenied) {
errorMsg = @"访问被拒绝";
}
if ([error code] == kCLErrorLocationUnknown) {
errorMsg = @"获取位置信息失败";
}
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Location"
message:errorMsg delegate:self cancelButtonTitle:@"Ok"otherButtonTitles:nil, nil];
[alertView show];
}
这样即可实现简单的定位。