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

iOS 地圖開發入門小結

編輯:iOS 開發綜合

幾個主要類別

  • MKMapView:地圖控制項,跟其他控制項一樣從物件庫拖進來就能用,負責顯示地圖內容。使用者可以對它做放大、縮小、拖動、旋轉等操作。
  • CLLocationCoordinate2D:座標結構,包含經度(longitude)與緯度(latitude)。
  • MKCoordinateSpan:地圖跨度,決定地圖的放大倍數,數值越小,顯示的單位越精細。
  • CLLocationManager:位置管理類別,用來取得使用者目前的 GPS 座標。

以下整理個人專案中地圖相關的入門知識,進階用法請參考其他資料。

一、地圖顯示

地圖顯示只要抓住兩個要素:中心座標點與地圖跨度。以中心點 (0, 0)、跨度 (8, 6) 為例,畫面上顯示的範圍就是 [-4, -3] 到 [4, 3]。

// 設定中心座標點
CLLocationCoordinate2D curLocation;
curLocation.latitude = 23.9098099;
curLocation.longitude = 112.980980;

// 設定地圖跨度
MKCoordinateSpan span;
span.latitudeDelta = 0.008;
span.longitudeDelta = 0.008;

// 套用並顯示
MKCoordinateRegion region = {curLocation, span};
[self.mapView setRegion:region animated:NO];

設定好中心座標與跨度後呼叫 setRegion: 即完成顯示,animated 參數決定切換時是否使用動畫。

二、定位並顯示目前位置

要取得目前位置並標在地圖上,就輪到 CLLocationManager 上場了,大致分為三個步驟。

第一步,建立並設定位置管理者:

if (self.locationManager == nil) {
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.distanceFilter = 1000.0;
    [self.locationManager startUpdatingLocation];
}

desiredAccuracy 決定定位精度,設為最佳精度會更耗電;distanceFilter 則是位移多少公尺才再次回呼,設 1000 代表移動超過一公里才更新。

第二步,在回呼方法中拿到座標並把地圖移過去:

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation {
    CLLocationCoordinate2D c = newLocation.coordinate;
    MKCoordinateSpan span = MKCoordinateSpanMake(0.01, 0.01);
    [self.mapView setRegion:MKCoordinateRegionMake(c, span) animated:YES];
}

第三步,記得在 Info.plist 中補上定位用途說明字串(NSLocationWhenInUseUsageDescription),否則 iOS 8 之後 requestWhenInUseAuthorization 不會正常跳出授權提示,直接取不到位置。此外還需在 didFailWithError: 中處理授權被拒絕或訊號不良的情況,避免使用者看到地圖一直停在預設位置卻不知原因。

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