MapView簡單定位及定位大頭針(Obj-C)

weixin_34087301發表於2016-07-10

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

相關文章