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

iOS 地圖開發入門:Core Location 與 Map Kit 基本用法

編輯:iOS 開發綜合

只要做過地圖類型的應用,就繞不開 Core Location 與 Map Kit 這兩支框架。前者負責「我在哪裡」,後者負責「把位置畫出來」。以下把最常用到的部分整理成一份可複習的筆記。

先確認裝置是否支援

並非所有 iOS 裝置都具備完整的定位與電子羅盤能力,所以在開始定位前先做判斷是個好習慣:

BOOL locationAvailable = [CLLocationManager locationServicesEnabled];
BOOL headingAvailable   = [CLLocationManager headingAvailable];

CLLocationManager:取得位置

CLLocationManager *locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = 1000;                    // 位移超過 1 km 才通知
locationManager.desiredAccuracy = kCLLocationAccuracyKilometer;

if ([CLLocationManager locationServicesEnabled]) {
    [locationManager startUpdatingLocation];
} else {
    NSLog(@"Location services not enabled.");
}

兩個屬性值得特別說明:

  • distanceFilter 決定「移動多遠才回報一次」。設成 1000 代表位置變動超過一公里才觸發 delegate,能有效降低耗電與不必要的回調。
  • desiredAccuracy 決定精度等級。級別越高越耗電,kCLLocationAccuracyKilometer 適合只需要「大概在哪座城市」的情境;導航類應用才需要 kCLLocationAccuracyBest。

實作 delegate

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation {
    NSLog(@"Moved from %@ to %@", oldLocation, newLocation);
}

- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error {
    NSLog(@"Received Core Location error %@", error);
    [manager stopUpdatingLocation];
}

除這兩個方法之外,CLLocationCoordinate2D 是 another 必備的型別——它用來表示經緯度座標,是位置資料在各框架之間傳遞的共通語言。

MKMapView:把地圖放進畫面

mapView.layer.cornerRadius = 10.0;      // 圓角
mapView.showsUserLocation = YES;        // 顯示使用者所在位置
[mapView setRegion:region animated:YES]; // 決定初始顯示哪個區域

setRegion:animated: 接收的是 MKCoordinateRegion,由中心座標與跨度(MKCoordinateSpan)組成,跨度就是你能控制的縮放層級。

兩個實務提醒

第一,從 iOS 8 開始,定位權限必須在執行期主動向使用者請求,並在 Info.plist 中補上 NSLocationWhenInUseUsageDescription 或 NSLocationAlwaysUsageDescription 說明用途,否則 App 會直接崩潰。這是新手最常踩的坑。

第二,showsUserLocation = YES 只是宣告「我想要顯示」,實際能不能取得位置仍取決於權限與硬體。追蹤使用者時,記得在離開頁面時呼叫 stopUpdatingLocation,否則背景定位會明顯拉高耗電,也容易在審核時被質疑。

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