天天看点

iOS定位 (一) 地图定位

带地图的定位方法
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
<MKMapViewDelegate>
//1.使用定位服务
    //设置app有访问定位服务的权限
    //在使用应用期间 / 始终(app在后台)
    //info.plist文件添加以下两条(或者其中一条):      这句话非常重要,关系到你能不能定位
    //NSLocationWhenInUseUsageDescription 在使用应用期间
    //NSLocationAlwaysUsageDescription  始终
    //2.LocationManager 对象管理相关的定位服务
    _manager = [[CLLocationManager alloc] init];
    //manager判断: 手机是否开启定位 / app是否有访问定位的权限
    //[CLLocationManager locationServicesEnabled]; //手机是否开启定位
    //[CLLocationManager authorizationStatus];  //app访问定位的权限的状态
    if (![CLLocationManager locationServicesEnabled] || [CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorizedWhenInUse) {
        [_manager requestWhenInUseAuthorization]; //向用户请求访问定位服务的权限
    }
//3.地图
    [self createMapView];

- (void)createMapView
{
    //创建MapView
    _mapView = [[MKMapView alloc] initWithFrame:self.view.bounds];
    //地图的类型
    _mapView.mapType = MKMapTypeStandard;
    //显示用户当前的位置
    //_mapView.userLocation
    //是否定位(是否追踪用户的位置)
    _mapView.userTrackingMode = MKUserTrackingModeFollow;
    _mapView.delegate = self;
    [self.view addSubview:_mapView];
}

//更新用户的位置
- (void)mapView:(MKMapView*)mapView didUpdateUserLocation:(MKUserLocation*)userLocation
{
    NSLog(@"location : %@", userLocation.location);
    //根据经纬度设置MapView
    //设置显示的区域范围, 设置显示的精度
    //设置显示的精度(比例尺)
    MKCoordinateSpan span = MKCoordinateSpanMake(0.01, 0.01);
    //指定的范围
    MKCoordinateRegion region = MKCoordinateRegionMake(userLocation.location.coordinate, span);
    //移动mapView显示的位置
    [_mapView setRegion:region animated:YES];
}