#mapKit使用最基本的例子
#终点在于注意在iOS8中定位增加的授权请求
1.在创建CLLocationManager后,需要进行定位授权。
-(CLLocationManager *)mgr { if (_mgr == nil) { _mgr = [[CLLocationManager alloc]init]; //定位授权 [_mgr requestAlwaysAuthorization]; [_mgr requestWhenInUseAuthorization]; //定位精度 _mgr.desiredAccuracy = kCLLocationAccuracyBest; //更新距离 _mgr.distanceFilter = 10; _mgr.delegate = self; } return _mgr; }
2.并在info.plist中配置如下两个key信息,string的内容根据实际需求填写。
完整代码如下:
#import "ViewController.h" #import <MapKit/MapKit.h> #import <CoreLocation/CoreLocation.h> @interface ViewController ()<MKMapViewDelegate, CLLocationManagerDelegate> /** * mapView,storyboard连接 */ @property (weak, nonatomic) IBOutlet MKMapView *mapView; /** * 按钮,回到定位位置,storyboard连接 */ - (IBAction)currentPosition; @property (nonatomic, strong) CLLocationManager *mgr; @end @implementation ViewController -(CLLocationManager *)mgr { if (_mgr == nil) { _mgr = [[CLLocationManager alloc]init]; //定位授权 [_mgr requestAlwaysAuthorization]; [_mgr requestWhenInUseAuthorization]; //定位精度 _mgr.desiredAccuracy = kCLLocationAccuracyBest; //更新距离 _mgr.distanceFilter = 10; _mgr.delegate = self; } return _mgr; } - (void)viewDidLoad { [super viewDidLoad]; #warning IOS8中变化 /* 1.定位授权 requestWhenInUseAuthorization() requestAlwaysAuthorization() 2.info.plist配置这两个key NSLocationAlwaysUsageDescription NSLocationWhenInUseUsageDescription */ //0.开始定位 [self.mgr startUpdatingLocation]; //1.跟踪用户位置 self.mapView.userTrackingMode = MKUserTrackingModeFollow; self.mapView.showsUserLocation = YES; //2.设置地图类型 self.mapView.mapType = MKMapTypeStandard; //3.设置地图代理 self.mapView.delegate = self; } #pragma mark - 关闭定位 -(void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; //停止定位 [self.mgr stopUpdatingLocation]; } #pragma mark - MKMapViewDelegate #pragma mark 位置改变 -(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation { NSLog(@"didUpdateUserLocation:%@",userLocation.location); //位置描述标题 userLocation.title = @"我在这里"; userLocation.subtitle = @"我真的在这里"; //中心 CLLocationCoordinate2D center = userLocation.coordinate; //显示经纬跨度 MKCoordinateSpan span = MKCoordinateSpanMake(0.002214, 0.001751); //范围 MKCoordinateRegion region = MKCoordinateRegionMake(center, span); //设置范围 [mapView setRegion:region animated:YES]; } #pragma mark MKMapViewDelegate代理方法,显示区域改变 -(void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated { NSLog(@"center.latitude:%f--center.longitude:%f", mapView.region.center.latitude, mapView.region.center.longitude); NSLog(@"span.latitudeDelta:%f--span.longitudeDelta:%f", mapView.region.span.latitudeDelta, mapView.region.span.longitudeDelta); } #pragma mark - CLLocationManagerDelegate代理方法 -(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations { NSLog(@"%@",[locations firstObject]); } #pragma mark - 回到定位位置 - (IBAction)currentPosition { [self.mapView setCenterCoordinate:self.mapView.userLocation.location.coordinate animated:YES]; } @end
时间: 2024-12-20 16:31:05