#import "ViewController.h" #import <MapKit/MapKit.h> @interface ViewController ()<MKMapViewDelegate> @property (weak, nonatomic) IBOutlet MKMapView *mapView; @property (nonatomic, strong) CLLocationManager * manager; @end @implementation ViewController //返回用户当前位置 - (IBAction)currentLocation:(id)sender { //获取用户所在的经纬度 CLLocationCoordinate2D coordinate = self.mapView.userLocation.location.coordinate; MKCoordinateSpan span = MKCoordinateSpanMake(0.1, 0.1); MKCoordinateRegion region = MKCoordinateRegionMake(coordinate, span); //定位可见区域 [self.mapView setRegion:region animated:YES]; } - (CLLocationManager *)manager { if (!_manager) { //创建定位管理器 CLLocationManager * locationManager = [[CLLocationManager alloc] init]; //定位的精确度,精确度越高越耗电 locationManager.desiredAccuracy = kCLLocationAccuracyBest; //定位的更新频率,单位为米 locationManager.distanceFilter = 5; _manager = locationManager; } return _manager; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. //iOS8的做法 if (![CLLocationManager locationServicesEnabled]) { NSLog(@"提示用户打开定位服务"); } else { //获取当前定位的状态 CLAuthorizationStatus status = [CLLocationManager authorizationStatus]; //如果定位状态为未打开 if (status == kCLAuthorizationStatusNotDetermined) { //requestWhenInUseAuthorization 前端定位 //requestAlwaysAuthorization 前端和后台定位 [self.manager requestWhenInUseAuthorization]; // [self.manager requestAlwaysAuthorization]; } } self.mapView.delegate = self; /* MKMapTypeStandard = 0,//标准地图2D MKMapTypeSatellite, //卫星地图 MKMapTypeHybrid, //混合地图 */ //设置地图类型 self.mapView.mapType = MKMapTypeStandard; //显示用户位置 self.mapView.showsUserLocation = YES; } //当用户位置改变时,调用。 - (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation { //获取当前用户的经纬度 CLLocationCoordinate2D coordinate = userLocation.location.coordinate; //将当前屏幕设为中心点 // [mapView setCenterCoordinate:coordinate animated:YES]; /* typedef struct { CLLocationDegrees latitudeDelta; 纬度跨度 CLLocationDegrees longitudeDelta; 经度跨度 } MKCoordinateSpan; typedef struct { CLLocationCoordinate2D center; 中心 MKCoordinateSpan span; } MKCoordinateRegion; */ //设置屏幕显示区域的经纬跨度 MKCoordinateSpan span = MKCoordinateSpanMake(0.1, 0.1); MKCoordinateRegion region = MKCoordinateRegionMake(coordinate, span); //定位可见区域 [mapView setRegion:region animated:YES]; }
原文:http://www.cnblogs.com/ldnh/p/5334358.html