1.添加MapKit.framework框架 ,在plist中添加字段,用于,获取用户当前位置设置
NSLocationAlwaysUsageDescription
2.代码
#import "ViewController.h"
#import <MapKit/MapKit.h>
@interface ViewController ()<MKMapViewDelegate>
@property (weak, nonatomic) IBOutlet MKMapView *mapKit;
//位置信息
@property(nonatomic,strong)CLLocation*location;
//地理编码对象
@property(nonatomic,strong)CLGeocoder*geocide;
@property(nonatomic,strong)CLLocationManager*manager;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//地图显示的类型
//MKMapTypeStandard:标准类型
//MKMapTypeSatellite:卫星模型
//MKMapTypeHybrid:混合模型
self.mapKit.mapType=MKMapTypeStandard;
// ios8中追踪用户位置
if([[UIDevice currentDevice].systemVersion doubleValue]>8.0)
{
self.manager =[[CLLocationManager alloc]init];
[self.manager requestAlwaysAuthorization];
}
//设置不允许地图旋转
self.mapKit.rotateEnabled=NO;
self.mapKit.delegate=self;
//设置mapKit获取用户位置的方式
// MKUserTrackingModeNone 不追踪
// MKUserTrackingModeFollow 追踪
// MKUserTrackingModeFollowWithHeading 追踪并获取用户的方向
self.mapKit.userTrackingMode=MKUserTrackingModeFollowWithHeading;
}
-(CLGeocoder*)geocide
{
if (_geocide==nil) {
_geocide=[[CLGeocoder alloc]init];
}
return _geocide;
}
-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
//利用地理编码获取位置,设置标题
[self.geocide reverseGeocodeLocation:userLocation.location completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark *mark=[placemarks firstObject];
userLocation.title=mark.name;
userLocation.subtitle=mark.locality;
}];
//利用地图当前的位置设置显示的区域
CLLocationCoordinate2D center=userLocation.location.coordinate;
//指定纬度的跨度
MKCoordinateSpan span=MKCoordinateSpanMake(0.009310,0.007812);
//指定显示区域的中
MKCoordinateRegion region=MKCoordinateRegionMake(center, span);
//设置显示区域
[self .mapKit setRegion:region];
}
-(void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
//地图区域改变完成
NSLog(@"%f,%f",self.mapKit.region.span.latitudeDelta,self.mapKit.region.span.longitudeDelta);
}
@end