以下整理個人專案中地圖相關的入門知識,進階用法請參考其他資料。
地圖顯示只要抓住兩個要素:中心座標點與地圖跨度。以中心點 (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: 中處理授權被拒絕或訊號不良的情況,避免使用者看到地圖一直停在預設位置卻不知原因。