天天看點

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];
}