標籤:
【實現功能】:
1.展示簡單地圖
2.顯示使用者當前位置
3.控制視圖大小
4.圖釘點擊顯示資訊
【實現步驟】
1.匯入兩個需要的架構:CoreLocation.framework和MapKit.framework
2.引入標頭檔:
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
3.需要兩個類的變數,這裡定義為屬性:
@property (nonatomic, retain)MKMapView *mapView;
@property (nonatomic, retain)CLLocationManager *locaManager;
4.別忘了接受協議
@interface ViewController ()<CLLocationManagerDelegate,MKMapViewDelegate>
5.OK開始上代碼
1 - (void)viewDidLoad{ 2 [super viewDidLoad]; 3 4 //初始化位置管理 5 self.locaManager = [[CLLocationManager alloc] init]; 6 //如果裝置在iOS8及以上,得先彈框讓使用者授權,才能獲得定位許可權 7 if ([[UIDevice currentDevice].systemVersion doubleValue] >= 8.0) { 8 [self.locaManager requestWhenInUseAuthorization]; 9 }10 //設定代理11 self.locaManager.delegate = self;12 //開始定位13 [self.locaManager startUpdatingLocation];14 15 16 //初始化地圖視圖17 self.mapView = [[MKMapView alloc] initWithFrame:self.view.frame];18 //設定地圖樣式為基本樣式(這裡有三種樣式)19 self.mapView.mapType = MKMapTypeStandard;20 //是否顯示當前位置21 self.mapView.showsUserLocation = YES;22 //設定代理23 self.mapView.delegate = self;24 [self.view addSubview:self.mapView];25 }
代理方法的實現
#pragma mark -- mapViewDelegate- (void)mapViewDidFinishLoadingMap:(MKMapView *)mapView{ NSLog(@"載入完畢");}- (void)mapViewWillStartLocatingUser:(MKMapView *)mapView{ NSLog(@"將要擷取使用者位置");}- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation{ //點擊圖釘,出現資訊 userLocation.title = @"丁健"; userLocation.subtitle = @"dingjianjaja"; //讓地圖視圖轉移到使用者當前位置 [mapView setCenterCoordinate:userLocation.location.coordinate animated:YES]; //設定精度,以及顯示使用者所在地 MKCoordinateSpan span = MKCoordinateSpanMake(1, 1);//比例尺為1:10^5,1厘米代表1公裡 MKCoordinateRegion region = MKCoordinateRegionMake(userLocation.location.coordinate, span); [mapView setRegion:region animated:YES];}
6.運行
發現不顯示使用者位置,原因是在iOS8以後程式使用定位有三種狀態,即試用期間/始終/永不,所以我們需要在plist檔案中配置:試用期間或者始終
NSLocationWhenInUseUsageDescription
簡單的展示地圖自己位置就完成了,下面會繼續加入目的地圖釘,以及串連當前位置與目的地,並計算直線距離的功能。
iOS開發-蘋果內建地圖簡單使用