國內的地圖服務普遍採用「火星座標」(GCJ-02)加密,直接拿 CLLocationManager 回傳的 GPS 原始座標去對位,會出現幾十到幾百公尺的偏移。本文示範如何取得定位座標、做反向地理編碼,以及在 GPS、火星、百度三種座標系之間轉換。
需要引入兩個框架:CoreLocation 負責取座標,MapKit 提供地圖與反向地理編碼能力。
// AppDelegate.h
#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate,
CLLocationManagerDelegate,
MKReverseGeocoderDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
#import "AppDelegate.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
UIButton *button = [UIButton buttonWithType:UIButtonTypeContactAdd];
button.frame = CGRectMake(0, 100, 100, 30);
[button setTitle:@"定位" forState:UIControlStateNormal];
[button addTarget:self action:@selector(test) forControlEvents:UIControlEventTouchUpInside];
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 150, 320, 30)];
label.tag = 101;
label.text = @"等待定位中....";
[self.window addSubview:label];
[label release];
[self.window addSubview:button];
return YES;
}
- (void)test {
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
// 定位精度:十公尺、百米、最佳
[locationManager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
locationManager.delegate = self;
[locationManager startUpdatingLocation];
}
// 定位失敗
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
NSLog(@"error");
}
// iOS 6 以後使用這個回呼
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
NSLog(@"%d", [locations count]);
CLLocation *newLocation = locations[0];
CLLocationCoordinate2D oldCoordinate = newLocation.coordinate;
NSLog(@"舊的經度:%f,舊的緯度:%f", oldCoordinate.longitude, oldCoordinate.latitude);
// 兩個座標之間的距離(公尺)
// float distance = [newLocation distanceFromLocation:oldLocation];
[manager stopUpdatingLocation];
// ---- 反向地理編碼:座標 → 地址(iOS 5 以後的寫法)----
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
for (CLPlacemark *place in placemarks) {
UILabel *label = (UILabel *)[self.window viewWithTag:101];
label.text = place.name;
NSLog(@"name,%@", place.name); // 位置名
// NSLog(@"thoroughfare,%@", place.thoroughfare); // 街道
// NSLog(@"subThoroughfare,%@", place.subThoroughfare); // 子街道
// NSLog(@"locality,%@", place.locality); // 城市
// NSLog(@"subLocality,%@", place.subLocality); // 行政區
// NSLog(@"country,%@", place.country); // 國家
}
}];
}
@end
幾個實務提醒:distanceFilter 決定要移動多少公尺才觸發一次回呼,預設是 0(每次變化都回報),電量敏感的場景應設為合理值;desiredAccuracy 越高越耗電,一般頁面用 kCLLocationAccuracyHundredMeters 就夠;另外記得在 Info.plist 補上 NSLocationWhenInUseUsageDescription,否則 App 會直接崩潰。
以下 GPScombineClass 負責定位、座標轉換與地圖顯示。GPS 到火星座標的轉換在實務上有兩種做法:查表法與演算法。這裡採用查表——把偏移量預先算好存進 sqlite,依經緯度取整後查對應的補正值,速度快且精度可控。
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
#import "CSqlite.h"
#import <MapKit/MapKit.h>
@interface GPScombineClass : NSObject <MKMapViewDelegate>
{
CLLocationManager *locationManager;
CSqlite *m_sqlite;
UILabel *m_locationName;
MKMapView *mainMapView;
@public
CLLocationCoordinate2D baidulocation; // 百度座標
CLLocationCoordinate2D deleeverLocation; // 火星座標
}
- (void)OpenGPSmapView;
// 在地圖上標出自己的位置(對外介面)
- (void)setMyMapPonitByMKMapView:(MKMapView *)MyMap;
@end
// 地圖上的標記物件
@interface POI : NSObject <MKAnnotation>
{
CLLocationCoordinate2D coordinate;
NSString *subtitle;
NSString *title;
}
@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
@property (nonatomic, retain) NSString *subtitle;
@property (nonatomic, retain) NSString *title;
- (id)initWithCoords:(CLLocationCoordinate2D)coords;
@end
#import "GPScombineClass.h"
const double x_pi = 3.14159265358979324 * 3000.0 / 180.0;
@implementation GPScombineClass
- (void)OpenGPSmapView {
m_sqlite = [[CSqlite alloc] init];
[m_sqlite openSqlite];
// 先確認定位服務可用
if ([CLLocationManager locationServicesEnabled]) {
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = 0.5;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
NSLog(@"GPS 啟動");
}
// 定位成功
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
CLLocationCoordinate2D mylocation = newLocation.coordinate; // 手機原始 GPS
mylocation = [self zzTransGPS:mylocation]; // 轉為火星座標
deleeverLocation = mylocation;
baidulocation = [self hhTrans_bdGPS:mylocation]; // 再轉為百度座標
}
// 定位失敗
- (void)locationManager:(CLLocationManager *)manager
didFailWithError:(NSError *)error {
NSLog(@"定位失敗");
}
// GPS → 火星座標(查表法)
- (CLLocationCoordinate2D)zzTransGPS:(CLLocationCoordinate2D)yGps {
int TenLat = 0;
int TenLog = 0;
// 取經緯度乘以 10 後的整數部分作為查詢鍵
TenLat = (int)(yGps.latitude * 10);
TenLog = (int)(yGps.longitude * 10);
NSString *sql = [[NSString alloc] initWithFormat:@"select offLat,offLog from gpsT where lat=%d and log = %d", TenLat, TenLog];
NSLog(sql);
sqlite3_stmt *stmtL = [m_sqlite NSRunSql:sql];
int offLat = 0;
int offLog = 0;
while (sqlite3_step(stmtL) == SQLITE_ROW) {
offLat = sqlite3_column_int(stmtL, 0);
offLog = sqlite3_column_int(stmtL, 1);
}
// 偏移量表中的數值放大了一萬倍儲存,這裡還原
yGps.latitude = yGps.latitude + offLat * 0.0001;
yGps.longitude = yGps.longitude + offLog * 0.0001;
return yGps;
}
// 火星座標 → 百度座標
- (CLLocationCoordinate2D)hhTrans_bdGPS:(CLLocationCoordinate2D)fireGps {
CLLocationCoordinate2D bdGps;
double huo_x = fireGps.longitude;
double huo_y = fireGps.latitude;
double z = sqrt(huo_x * huo_x + huo_y * huo_y) + 0.00002 * sin(huo_y * x_pi);
double theta = atan2(huo_y, huo_x) + 0.000003 * cos(huo_x * x_pi);
bdGps.longitude = z * cos(theta) + 0.0065;
bdGps.latitude = z * sin(theta) + 0.006;
return bdGps;
}
// 百度座標 → 火星座標(反向公式)
- (CLLocationCoordinate2D)hhTrans_GCGPS:(CLLocationCoordinate2D)baiduGps {
CLLocationCoordinate2D googleGps;
double bd_x = baiduGps.longitude - 0.0065;
double bd_y = baiduGps.latitude - 0.006;
double z = sqrt(bd_x * bd_x + bd_y * bd_y) - 0.00002 * sin(bd_y * x_pi);
double theta = atan2(bd_y, bd_x) - 0.000003 * cos(bd_x * x_pi);
googleGps.longitude = z * cos(theta);
googleGps.latitude = z * sin(theta);
return googleGps;
}
// 把火星座標轉為百度座標後,在地圖上標記
- (void)showPurchaseOnMapByLocation:(CLLocationCoordinate2D)baiduGPS
MKMapView:(MKMapView *)myMapView {
CLLocationCoordinate2D googleGPS = [self hhTrans_GCGPS:baiduGPS];
[self SetPurchaseMapPoint:googleGPS MKMapView:myMapView];
}
- (void)SetPurchaseMapPoint:(CLLocationCoordinate2D)myLocation
MKMapView:(MKMapView *)mapView {
POI *m_poi = [[POI alloc] initWithCoords:myLocation];
[mapView addAnnotation:m_poi];
MKCoordinateRegion theRegion = { {0.0, 0.0}, {0.0, 0.0} };
theRegion.center = myLocation;
[mapView setZoomEnabled:YES];
[mapView setScrollEnabled:YES];
theRegion.span.longitudeDelta = 0.01f;
theRegion.span.latitudeDelta = 0.01f;
[mapView setRegion:theRegion animated:YES];
}
@end
關於查表法。它的優點是查詢極快、精度由表格密度決定;缺點是必須預先準備偏移量表,且需要額外維護 sqlite 資源。若不想依賴外部表格,實務上更常見的是直接採用演算法(把中國境內座標視為偏移量做非線性修正),或乾脆改用高德、百度等官方 SDK——它們會在內部完成座標轉換,你只需要處理自己系統與 SDK 之間的一次轉換。
關於精度與電池。範例把 desiredAccuracy 設為 kCLLocationAccuracyBest 且 distanceFilter 設為 0.5,這是相當耗電的組合。若只是要在地圖上顯示大概位置,請調降精度並放寬距離門檻。
關於 SQL 與記憶體。範例用 initWithFormat 拼接 SQL,正式環境請改用參數綁定以避免注入風險;sqlite3_stmt 使用完畢也應呼叫 sqlite3_finalize 釋放。
關於定位失敗的處理。didFailWithError 只印了一行 log。實務上應區分「使用者拒絕授權」、「定位服務關閉」、「暫時取不到訊號」三種情況,並給出對應的引導或重試機制。