//定位 需要在info中添加NSLocationWhenInUseUsageDescription
if ([[UIDevice currentDevice].systemVersion doubleValue]>=8.0) {
//获取权限
[self.locationManager requestWhenInUseAuthorization];
}
//开始定位
[self.locationManager startUpdatingLocation];
//懒加载
-(CLLocationManager *)locationManager{
if (!_locationManager) {
_locationManager=[[CLLocationManager alloc]init];
_locationManager.delegate=self; //
}
return _locationManager;
}
创建地图
self.mapView =[[MKMapView alloc]initWithFrame:[[UIScreen mainScreen]bounds]];
//1.跟踪用户位置(显示用户的具体位置)
self.mapView.userTrackingMode =MKUserTrackingModeFollow;
//2.设置地图类型
// self.mapView.mapType=MKMapTypeStandard;
//设置代理
self.mapView.delegate=self;
// self.mapView.showsUserLocation=YES;
[self.view addSubview:self.mapView];
#pragma mark - NKMapViewDelegate
//当用户的位置更新,就会调用(不断地监控用户的位置,调用频率特别高)
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{
// MKUserLocation 大头针模型对象
NSLog(@"%f %f",userLocation.location.coordinate.longitude ,userLocation.location.coordinate.latitude);
userLocation.title=@"天苍苍野茫茫风吹草地见牛羊";
userLocation.subtitle=@"床前光,地上霜";
//设置地图的中心点 ( 用户所在的区域)
// [mapView setCenterCoordinate:userLocation.location.coordinate animated:YES];]
//设置地图的显示范围
//设置跨度
MKCoordinateSpan span =MKCoordinateSpanMake(0.5,0.5);
CLLocationCoordinate2D center = userLocation.location.coordinate;
mapView.region=MKCoordinateRegionMake(center, span);
}
//获取当前跨度
-(void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
NSLog(@"%f %f",mapView.region.span.latitudeDelta,mapView.region.span.longitudeDelta);
}
添加大头针 (自己定义 需要创建一个遵守MKAnnotation协议的类)
#import <Foundation/Foundation.h> #import <MapKit/MapKit.h> @interface WBAnnotation : NSObject<MKAnnotation> @property (nonatomic,assign) CLLocationCoordinate2D coordinate; @property (nonatomic, copy) NSString *title; @property (nonatomic, copy) NSString *subtitle;
创建大头针
//创建手势
UITapGestureRecognizer * longpress =[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapMapVIew:)];
//添加手势
[self.mapView addGestureRecognizer:longpress];
//响应手势事件
- (void)tapMapVIew:(UITapGestureRecognizer * )tap{
//1.获得用户在地图点击的位置(x,y)
CGPoint point =[tap locationInView:tap.view];
//2.将数学坐标转为 地理经纬度坐标
CLLocationCoordinate2D coordinate= [self.mapView convertPoint:point toCoordinateFromView:self.mapView];
//3.创建大头针模型,添加大头针到地图上(自定义的大头针类)
WBAnnotation *anno =[[WBAnnotation alloc]init];
anno.coordinate =coordinate;
anno.title=@"大哥";
anno.subtitle=@"你好棒";
[self.mapView addAnnotation:anno];
}