MKMapView上獲取自身當前位置並將地圖顯示範圍控制在自身位置周圍
阿新 • • 發佈:2019-02-09
1,框架中新增CoreLocation.framework
2,引入標頭檔案#import <CoreLocation/CoreLocation.h>
3,使用相關協議
@interfaceARWUserMapAnnotationViewController ()<MKMapViewDelegate,CLLocationManagerDelegate>
4,宣告變數
@property (nonatomic, strong) MKMapView *selfMapView; @property (nonatomic, strong) CLLocationManager *locationManager; //使用者獲取位置 @property (nonatomic, strong) CLLocation *checkinLocation_MY; //儲存獲取的位置
5,載入地圖,並獲取當前位置
self.title = @"Map"; CGRect frame = [self.view bounds]; // Map View selfMapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)]; selfMapView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth; selfMapView.delegate = self; selfMapView.showsUserLocation = YES; UIBarButtonItem *backFromMapButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(doButtonBack)]; self.navigationItem.leftBarButtonItem = backFromMapButtonItem; [self.view addSubview:selfMapView]; //獲取當前位置 locationManager = [[CLLocationManager alloc] init]; //若開啟了允許獲取當前位置 if ([CLLocationManager locationServicesEnabled]) { NSLog( @"Starting CLLocationManager" ); locationManager.delegate = self; locationManager.distanceFilter = 200; locationManager.desiredAccuracy = kCLLocationAccuracyBest; [locationManager startUpdatingLocation]; } //若未開啟 else { NSLog( @"Cannot Starting CLLocationManager" ); }
6,實現協議
#pragma mark - CLLocationManagerDelegate Methods - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { checkinLocation_MY = newLocation; // Annotations [selfMapView addAnnotations:[self annotations]]; //地圖的範圍 越小越精確 MKCoordinateSpan theSpan; theSpan.latitudeDelta=20; theSpan.longitudeDelta=20; MKCoordinateRegion theRegion; theRegion.center=[[locationManager location] coordinate]; theRegion.span=theSpan; [selfMapView setRegion:theRegion]; }