需要导入的几个框架
#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
@interface ViewController ()<MKMapViewDelegate>
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic,strong) MKMapView *mapView;
@property (nonatomic, strong) CLGeocoder *geocoder;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 初始化
self.locationManager = [[CLLocationManager alloc] init];
// 设置代理
self.locationManager.delegate = self;
// 定位精度
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
// 设置多少米更新一次距离
self.locationManager.distanceFilter = 100;
// 请求位置信息
[self.locationManager requestAlwaysAuthorization];
// 开始请求位置信息
[self.locationManager startUpdatingLocation];
// 将位置信息装换为经纬度
[self.geocoder geocodeAddressString:@"北京" completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemack = [placemarks firstObject];
// 经度
CGFloat longitude = placemack.location.coordinate.longitude;
// 维度
CGFloat latitude = placemack.location.coordinate.latitude;
NSLog(@"地理位置!!!!! ~~维度%f 经度%f", latitude, longitude);
}];
// 地图初始化
self.mapView = [[MKMapView alloc] initWithFrame:self.view.bounds];
// 设置代理
self.mapView.delegate = self;
// 设置地图跟随移动
self.mapView.userTrackingMode = MKUserTrackingModeFollow;
// 设置地图样式
self.mapView.mapType = MKMapTypeStandard;
[self.view addSubview:self.mapView];
}
#pragma mark - 代理方法
// 定位成功
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *location = [locations firstObject];
NSLog(@"%@", location);
[self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
if (error) {
NSLog(@"%@", [error localizedDescription]);
} else {
CLPlacemark *placemark = [placemarks firstObject];
NSLog(@"%@", placemark.addressDictionary);
}
}];
}
// 定位失败
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
// 错误信息描述
NSLog(@"%@",[error localizedDescription]);
}
#pragma mark - 懒加载方法
- (CLGeocoder *)geocoder
{
if (!_geocoder) {
_geocoder = [[CLGeocoder alloc] init];
}
return _geocoder;
}