使用到的類庫
- MapKit.framework 地圖服務
- CoreLocation.framwork 定位服務
基本的顯示
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
// // ViewController.m // tryMapKit // // Created by Don on 2015/2/12. // Copyright (c) 2015年 DON (blog.devdon.com). All rights reserved. // #import "ViewController.h" #import <CoreLocation/CoreLocation.h> #import <MapKit/MapKit.h> @interface ViewController ()<MKMapViewDelegate,CLLocationManagerDelegate>{ } @property CLLocationManager *locationManager; @property MKMapView *mapView; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self initVC]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (void)initVC{ self.view.backgroundColor = [UIColor orangeColor]; self.locationManager = [[CLLocationManager alloc]init]; if (![CLLocationManager locationServicesEnabled]){ NSLog(@"用戶手機定位功能沒有打開"); } //如果沒有授權則跳出授權提示 if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusNotDetermined){ [_locationManager requestWhenInUseAuthorization]; }else if([CLLocationManager authorizationStatus]==kCLAuthorizationStatusAuthorizedWhenInUse){ //设置代理 _locationManager.delegate=self; //设置定位精度 _locationManager.desiredAccuracy=kCLLocationAccuracyBest; //定位频率,每隔多少米定位一次 CLLocationDistance distance=10.0;//十米定位一次 _locationManager.distanceFilter=distance; //启动跟踪定位 [_locationManager startUpdatingLocation]; } //設置顯示的view大小 self.mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0, 0, 320, 640)]; //地圖類型 self.mapView.mapType = MKMapTypeStandard; //設置代理 self.mapView.delegate = self; //显示当前位置 self.mapView.showsUserLocation = YES; [self.view addSubview:self.mapView]; } //讓地圖馬上跳到指定的座標,並拉近到經緯度為250,250的大小顯示(不拉近就是拉很遠看世界地圖那樣) -(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{ CLLocationCoordinate2D location = [userLocation coordinate]; MKCoordinateRegion region = MKCoordinateRegionMakeWithDistance(location, 1000, 1000); [self.mapView setRegion:region animated:YES]; } @end |
使用Mapkit要注意的地方
第一個-iOS 8以上版本 - 要給.plist增加東西
- NSLocationWhenInUseUsageDescription,只有打開APP的時候
- NSLocationAlwaysUsageDescription,任何時間
根據你想要用戶授權的類型來選擇添加上面兩個string類型的資料。
為什麼呢?因為iOS8以上版本,在要求用戶授權的時候,可以打上自定義的文字了。
這是請求用戶授APP定位功能,不是要用戶打開定位功能。
第二個-沒有出現我在哪裡
我一開始也很疑惑,在自己操作前先看了一個demo,一打開就定位到美國了,我以為模擬器打開來都會這樣,結果我自己操作的時候完全沒有那個藍色的點…..我想想如果開發人員在測試定位的時候,還要拿著電腦走動看看,那應該臉上會有幾條黑線吧~_~
果然,模擬器可以直接設定你傳送到的地點…
xcode中,在debug中可以看到location的設置,有默認選項,也可以自己打經緯度定位