您的位置:首页 > 其它

MapKit的基本使用

2015-11-08 17:47 351 查看


//
//  ViewController.m

#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>

@interface ViewController ()<CLLocationManagerDelegate,MKMapViewDelegate>
@property (weak, nonatomic) IBOutlet MKMapView *mapView;
/**
*  位置管理者对象
*/
@property(nonatomic,strong) CLLocationManager *locMgr;

- (IBAction)backToUserLocation:(UIButton *)sender;
@end

@implementation ViewController

/**
*  延迟创建定位管理者对象
*/
- (CLLocationManager *)locMgr
{
//如果定位服务不可用,加一个判断
if(![CLLocationManager locationServicesEnabled]) return nil;

if (_locMgr == nil) {
//创建定位管理者对象
self.locMgr =[[CLLocationManager alloc]init];
//设置代理
self.locMgr.delegate = self;
}
return _locMgr;
}

/**
*  回到用户所在位置
*/
- (IBAction)backToUserLocation:(UIButton *)sender {
[self.mapView setCenterCoordinate:self.mapView.userLocation.coordinate animated:YES];
}

- (void)viewDidLoad {
[super viewDidLoad];

/**
*  iOS 8之后要用户授权
具体操作:
在Info.plist文件还要加上NSLocationWhenInUseUsageDescription这个key,Value可以为空,
*/
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0){
[self.locMgr requestWhenInUseAuthorization];  //调用了这句,就会弹出允许框了.
}

/**
MKUserTrackingModeNone = 0, //不跟踪
MKUserTrackingModeFollow, //跟踪
MKUserTrackingModeFollowWithHeading, //前进方向
*/

//1.跟踪用户位置
self.mapView.userTrackingMode = MKUserTrackingModeFollow;

//2.设置地图类型(不设置默认为标准类型)
self.mapView.mapType = MKMapTypeStandard;

//3.设置mapView的代理
self.mapView.delegate = self;
}

#pragma mark - MKMapViewDelegate
/**
*  当用户的位置更新就会调用(不断地监控用户位置,调用频率特别高)
*
*  @param userLocation 表示地图上蓝色那颗大头针的数据
*/
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation
{
//点击大头针会显示出来
userLocation.title = @"中国北京";
userLocation.subtitle = @"北京是中国的首都";

//打印经纬度
//    NSLog(@"%f %f",userLocation.location.coordinate.longitude,userLocation.location.coordinate.latitude); //116.006140 40.001211

//设置地图的中心点(以用户所在的位置为中心点)
[mapView setCenterCoordinate:userLocation.location.coordinate animated:YES];

//设置地图显示范围
MKCoordinateSpan span = MKCoordinateSpanMake(0.2, 0.2);//设置经度跨度和纬度跨度
MKCoordinateRegion region = MKCoordinateRegionMake(userLocation.location.coordinate, span);
[mapView setRegion:region];
}

/**
*  监听mapView的经度跨度和纬度跨度
*
*/
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
NSLog(@"%f %f",mapView.region.span.longitudeDelta,mapView.region.span.latitudeDelta);
}
@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: