首先要做的準備
- 點擊工程名,滑到最下面,點擊+號,導入MapKit.framework系統庫。
- 如果你是iOS8及以上的版本,則需要在info.plist文件下加入以下的東西,最後面的字符大家可以隨便打,這個無所謂的。
demo的詳細做法
- 首先在storyboard裏面拖一個MapView,通過autoLayout添加約束讓他佔滿全屏。
- 在左下角拖一個button,設置他的普通圖片和高亮時候的圖片,這個button主要是爲了使用戶返回自己當前所在位置的。
- 將storyboard的兩個控件拉到ViewController中,這樣我們就可以得到他們的屬性了。
- 如果大家有誰在模擬器中運行的話,等模擬器運行後點擊上方的debug,進去之後點擊location,選擇第二個custom location在裏面設置你當前位置的經緯度,因爲模擬器是沒辦法定位的,他運行之後默認定位的是美國,所以大家需要改上面的東西,如果是真機,則不需要設置,直接就可以運行。
- 下面給大家展示demo做好之後的效果。
最後給大家奉上代碼,註釋寫的挺詳細的,相信你們可以看懂的。
#import "ViewController.h" #import <MapKit/MapKit.h> @interface ViewController ()<MKMapViewDelegate> @property (weak, nonatomic) IBOutlet MKMapView *mapView; @property (nonatomic, strong) CLLocationManager * manager; @end @implementation ViewController //返回用戶當前位置 - (IBAction)currentLocation:(id)sender { //獲取用戶所在的經緯度 CLLocationCoordinate2D coordinate = self.mapView.userLocation.location.coordinate; MKCoordinateSpan span = MKCoordinateSpanMake(0.1, 0.1); MKCoordinateRegion region = MKCoordinateRegionMake(coordinate, span); //定位可見區域 [self.mapView setRegion:region animated:YES]; } - (CLLocationManager *)manager { if (!_manager) { //創建定位管理器 CLLocationManager * locationManager = [[CLLocationManager alloc] init]; //定位的精確度,精確度越高越耗電 locationManager.desiredAccuracy = kCLLocationAccuracyBest; //定位的更新頻率,單位爲米 locationManager.distanceFilter = 5; _manager = locationManager; } return _manager; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. //iOS8的做法 if (![CLLocationManager locationServicesEnabled]) { NSLog(@"提示用戶打開定位服務"); } else { //獲取當前定位的狀態 CLAuthorizationStatus status = [CLLocationManager authorizationStatus]; //如果定位狀態爲未打開 if (status == kCLAuthorizationStatusNotDetermined) { //requestWhenInUseAuthorization 前端定位 //requestAlwaysAuthorization 前端和後臺定位 [self.manager requestWhenInUseAuthorization]; // [self.manager requestAlwaysAuthorization]; } } self.mapView.delegate = self; /* MKMapTypeStandard = 0,//標準地圖2D MKMapTypeSatellite, //衛星地圖 MKMapTypeHybrid, //混合地圖 */ //設置地圖類型 self.mapView.mapType = MKMapTypeStandard; //顯示用戶位置 self.mapView.showsUserLocation = YES; } //當用戶位置改變時,調用。 - (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation { //獲取當前用戶的經緯度 CLLocationCoordinate2D coordinate = userLocation.location.coordinate; //將當前屏幕設爲中心點 // [mapView setCenterCoordinate:coordinate animated:YES]; /* typedef struct { CLLocationDegrees latitudeDelta; 緯度跨度 CLLocationDegrees longitudeDelta; 經度跨度 } MKCoordinateSpan; typedef struct { CLLocationCoordinate2D center; 中心 MKCoordinateSpan span; } MKCoordinateRegion; */ //設置屏幕顯示區域的經緯跨度 MKCoordinateSpan span = MKCoordinateSpanMake(0.1, 0.1); MKCoordinateRegion region = MKCoordinateRegionMake(coordinate, span); //定位可見區域 [mapView setRegion:region animated:YES]; }