您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 系統地圖實作:MKMapView 定位與標註完整流程

編輯:iOS 開發綜合

要用 Apple 自帶的地圖顯示使用者位置並落下標註,核心就是兩個框架:CoreLocation 負責取經緯度,MapKit 負責渲染。整個流程可以拆成「引入框架 → 建立定位管理器 → 建立地圖 → 更新標註」四步。

第一步:加入框架

在專案設定的 Linked Frameworks and Libraries 中新增 CoreLocation.framework 與 MapKit.framework,並在檔案頂部引入對應頭檔。

第二步:宣告屬性

@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) MKMapView       *mapView;
@property (nonatomic, strong) CLLocation      *checkinLocation;
@property (strong, nonatomic) NSString *currentLatitude;   // 緯度
@property (strong, nonatomic) NSString *currentLongitude;  // 經度

第三步:初始化

在 viewDidLoad 中依序完成標題、右上角按鈕、定位管理器與地圖的設定。

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"地圖";
    [self initRightBarButton];
    [self setupLocationManager];
    [self setupMapView];
}

右上角放一顆定位按鈕,點擊後把地圖中心移到使用者所在位置:

-(void)initRightBarButton {
    UIButton *btnRight = [UIButton buttonWithType:UIButtonTypeCustom];
    btnRight.frame = CGRectMake(0, 0, 39, 34);
    [btnRight setBackgroundImage:[UIImage imageNamed:@"gpsbtn_dianji"] forState:UIControlStateNormal];
    [btnRight setBackgroundImage:[UIImage imageNamed:@"gpsbtn"]      forState:UIControlStateSelected];
    btnRight.showsTouchWhenHighlighted = YES;
    [btnRight addTarget:self action:@selector(showUserLocation:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem =
        [[UIBarButtonItem alloc] initWithCustomView:btnRight];
}

第四步:設定定位管理器

- (void)setupLocationManager {
    _locationManager = [[CLLocationManager alloc] init];
    _locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
    // 任何移動都回報
    _locationManager.distanceFilter = kCLDistanceFilterNone;

    // iOS 8 之後必須主動請求授權
    if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
        [self.locationManager requestWhenInUseAuthorization];
        [self.locationManager startUpdatingLocation];
    }
}

iOS 8 起授權變成非同步流程,除了程式碼請求,還要在 Info.plist 補上 NSLocationWhenInUseUsageDescription(或 Always 版本)的說明文字,否則授權彈窗不會出現、定位也會靜默失敗。

第五步:建立地圖並追蹤使用者

- (void)setupMapView {
    _mapView = [[MKMapView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:_mapView];
    _mapView.delegate = self;
    // 追蹤模式會同時觸發定位服務
    _mapView.userTrackingMode = MKUserTrackingModeFollowWithHeading;
    _mapView.mapType = MKMapTypeStandard;
    [self initLocationData];
}

第六步:接收座標並更新標註

- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
    NSLog(@"緯度:%f 經度:%f",
          userLocation.location.coordinate.latitude,
          userLocation.location.coordinate.longitude);
    self.currentLatitude  = [NSString stringWithFormat:@"%.4f", userLocation.location.coordinate.latitude];
    self.currentLongitude = [NSString stringWithFormat:@"%.4f", userLocation.location.coordinate.longitude];
    [self initLocationData];
}

- (void)initLocationData {
    NSMutableArray *arr = [[NSMutableArray alloc] init];
    CLLocationDegrees lat  = [self.currentLatitude doubleValue];
    CLLocationDegrees longi = [self.currentLongitude doubleValue];
    BasicMapAnnotation *anno =
        [[BasicMapAnnotation alloc] initWithLatitude:lat andLongitude:longi];
    anno.title = @"當前位置";
    anno.index = 0;
    [arr addObject:anno];
    [_mapView showAnnotations:arr animated:YES];
}

- (void)showUserLocation:(id)sender {
    MKCoordinateSpan span = MKCoordinateSpanMake(0.01, 0.02);
    MKCoordinateRegion region = MKCoordinateRegionMake(_mapView.userLocation.coordinate, span);
    [_mapView setRegion:region animated:YES];
}

第七步:自訂標註樣式

透過 viewForAnnotation: 可以換掉系統預設的紅色大頭針,這裡用一個 14×35 的圖片視圖覆蓋上去,並開啟氣泡(callout)。

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id)annotation {
    if ([annotation isKindOfClass:[BasicMapAnnotation class]]) {
        static NSString *key = @"AnnotationKey";
        MKAnnotationView *annotationView = [_mapView dequeueReusableAnnotationViewWithIdentifier:key];
        if (!annotationView) {
            annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:key];
            CGRect frame = annotationView.frame;
            frame.size.width  = 14;
            frame.size.height = 35;
            annotationView.frame = frame;
            annotationView.canShowCallout = YES;
            UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"地圖標注"]];
            imageView.frame = frame;
            [annotationView addSubview:imageView];
        }
        return annotationView;
    }
    return nil;
}

最後別忘了在 didReceiveMemoryWarning 之外,於合適的時機(例如 viewWillDisappear)呼叫 [_locationManager stopUpdatingLocation],避免持續定位耗電。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved