MapView简单定位及定位大头针(Obj-C)

1.导入头文件

如果使用代码创建,会自动导入MapKit框架,如果使用Xib/SB,需要手动导入MapKit.framework框架

2.请求授权(记得配置info.plist文件)

如果忘记请求授权,控制台会弹出错误:

 Trying to start MapKit location updates without prompting for location authorization. Must call -[CLLocationManager requestWhenInUseAuthorization] or -[CLLocationManager requestAlwaysAuthorization] first.
#import "ViewController.h"
#import 

@interface ViewController () 
// MapView
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
// 定位管理者
@property (nonatomic,strong) CLLocationManager *manager;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 请求授权
    self.manager = [[CLLocationManager alloc]init];
    
    if ([self.manager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
        
        [self.manager requestWhenInUseAuthorization];
    }
    
    // 地图定位  设置用户的跟踪模式
    /*
     MKUserTrackingModeNone = 0, // the user's location is not followed
     MKUserTrackingModeFollow, // the map follows the user's location
     MKUserTrackingModeFollowWithHeading __TVOS_PROHIBITED, // the map follows the user's location and heading
     */
    self.mapView.userTrackingMode = MKUserTrackingModeFollow;
    
    // 设置代理
    self.mapView.delegate = self;
    

}
/**
 *  已经更新用户的位置后调用
 *
 *  @param mapView      地图视图
 *  @param userLocation 定位大头针模型
 */
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
    
    // 创建地理编码者
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:self.mapView.userLocation.location completionHandler:^(NSArray * _Nullable placemarks, NSError * _Nullable error) {
        if (placemarks.count == 0 || error) {
            return ;
        }
        CLPlacemark *pm = placemarks.lastObject;
        
        //大头针视图不是由开发者来添加的,大头针视图的数据是由开发者来设置的,通过大头针视图的大头针模型来设置  定位大头针的模型类为MKUserLocation
        //2.4设置数据
        self.mapView.userLocation.title = pm.locality;
        self.mapView.userLocation.subtitle = pm.name;
    }];
    

    
}

@end

你可能感兴趣的:(MapView简单定位及定位大头针(Obj-C))