苹果MapKit实现简单定位功能

1 声明一个位置管理的属性

@property (nonatomic, strong) CLLocationManager* locationManager;//CLLocationManagerDelegate(代理方法)

2 初始化对象

self.locationManager = [[CLLocationManager alloc] init];

self.locationManager.delegate = self;

self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;

if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {

NSLog(@"requestWhenInUseAuthorization");

[self.locationManager requestWhenInUseAuthorization];

}

//开始定位,不断调用其代理方法

[self.locationManager startUpdatingLocation];


3 记录位置信息

- (void)locationManager:(CLLocationManager *)manager

didUpdateLocations:(NSArray *)locations

{

// 1.获取用户位置的对象

CLLocation *location = [locations lastObject];

// 2.停止定位

[manager stopUpdatingLocation];

float altitude = location.altitude;

//    NSLog(@"海拔高度为:%.2fm",altitude);

//    NSLog(@"垂直精度为:%.2fm",location.verticalAccuracy);

//    NSLog(@"当前速度:%.2fm",location.speed);

CLLocationCoordinate2D coordinate = location.coordinate;

//    NSLog(@"纬度:%f 经度:%f", coordinate.latitude, coordinate.longitude);

CLGeocoder *geocoder = [[CLGeocoder alloc] init];

//根据经纬度反向地理编译出地址信息

[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *array, NSError *error){

if (array.count > 0){

CLPlacemark *placemark = [array objectAtIndex:0];

_city = placemark.locality;

if (!_city) {

//四大直辖市的城市信息无法通过locality获得,只能通过获取省份的方法来获得(如果city为空,则可知为直辖市)

_city = placemark.administrativeArea;

}

//          NSLog(@"city--= %@", _city);

[self.destinationBtn setTitle:_city forState:UIControlStateNormal];

}

else if (error == nil && [array count] == 0)

{

NSLog(@"No results were returned.");

}

else if (error != nil)

{

//            NSLog(@"An error occurred = %@", error);

}

}];

}

你可能感兴趣的:(苹果MapKit实现简单定位功能)