一個關於定位的demo,一個定位demo
首先要做的準備
- 點擊工程名,滑到最下面,點擊+號,匯入MapKit.framework系統庫。
- 如果你是iOS8及以上的版本,則需要在info.plist檔案下加入以下的東西,最後面的字元大家可以隨便打,這個無所謂的。
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];}