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

1.导入头文件 <MapKit/MapKit.h>

如果使用代码创建,会自动导入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 <MapKit/MapKit.h>

@interface ViewController () <MKMapViewDelegate>
// 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<CLPlacemark *> * _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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,967评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,420评论 25 708
  • 不知不觉喜欢上了画画,有了绘画,我不在孤单,没事的时候,拿起笔,一画就是一两个小时,不仅仅能度过没事的时间,还能够...
    梦想的翅膀_0bbf阅读 579评论 2 1
  • 还记得今年给自己定的学习主线就是向内探寻,寻找自己生命的支持力量。一直以来,都觉得自己会多多少少有些讨好型人格,从...
    竹溪Sophie阅读 245评论 0 0
  • 今天在朋友圈看到一位朋友推荐的视频《Turning point》,一则只有16分钟的短片,却无比温馨感人,在此...
    步步微风起阅读 519评论 0 0