做地圖相關功能時,最容易被忽略的細節是座標系不一致。手機 GPS 給出的是 WGS-84,而 Google 地圖用的是 GCJ-02(俗稱火星座標),百度又自有一套 BD-09。混用而不轉換,結果就是定位點偏移幾百公尺。以下把整個流程整理成一個可重用的公共類別。
這個類別負責四件事:啟動定位、取得 GPS 座標、把手機座標轉為火星座標、以及在需要時於火星座標與百度座標之間雙向轉換,最後把位置畫到地圖上。
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>
#import "CSqlite.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
啟動前先檢查定位服務是否可用,並記得設定 delegate:
- (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];
}
}
- (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(@"定位失敗");
}
這裡的關鍵觀念是:一次定位,兩種座標都先算好存起來。後續要顯示在哪個地圖上,直接取對應的那份即可,不必重複換算。
若需要把座標變成「台北市大安區…」這樣的文字,用 CLGeocoder:
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
if (placemarks.count > 0) {
CLPlacemark *plmark = [placemarks objectAtIndex:0];
NSLog(@"%@-%@-%@", plmark.country, plmark.locality, plmark.name);
self->m_locationName.text = plmark.name;
}
}];
注意這個 API 有呼叫頻率限制,不適合在每次位置更新時都呼叫,實務上應該搭配節流或只在使用者要求時觸發。
這裡採用的是查表法:把經緯度各乘以 10 取整數當索引,從預先建好的偏移量表撈出修正值。
const double x_pi = 3.14159265358979324 * 3000.0 / 180.0;
- (CLLocationCoordinate2D)zzTransGPS:(CLLocationCoordinate2D)yGps {
int TenLat = (int)(yGps.latitude * 10);
int TenLog = (int)(yGps.longitude * 10);
NSString *sql = [NSString stringWithFormat:
@"select offLat,offLog from gpsT where lat=%d and log=%d", TenLat, TenLog];
sqlite3_stmt *stmtL = [m_sqlite NSRunSql:sql];
int offLat = 0, offLog = 0;
while (sqlite3_step(stmtL) == SQLITE_ROW) {
offLat = sqlite3_column_int(stmtL, 0);
offLog = sqlite3_column_int(stmtL, 1);
}
yGps.latitude += offLat * 0.0001;
yGps.longitude += offLog * 0.0001;
return yGps;
}
實務提醒:查表法的精度取決於表格密度,且無法涵蓋表外區域。若專案允許,改用演算法換算(業界常用的 eviltransform / GCJ-02 轉換公式)會更穩定,不必依賴外部資料檔。
這兩個之間是純演算法轉換,不需要查表:
// 火星 → 百度
- (CLLocationCoordinate2D)hhTrans_bdGPS:(CLLocationCoordinate2D)fireGps {
double x = fireGps.longitude, y = fireGps.latitude;
double z = sqrt(x * x + y * y) + 0.00002 * sin(y * x_pi);
double theta = atan2(y, x) + 0.000003 * cos(x * x_pi);
CLLocationCoordinate2D bdGps;
bdGps.longitude = z * cos(theta) + 0.0065;
bdGps.latitude = z * sin(theta) + 0.006;
return bdGps;
}
// 百度 → 火星
- (CLLocationCoordinate2D)hhTrans_GCGPS:(CLLocationCoordinate2D)baiduGps {
double x = baiduGps.longitude - 0.0065;
double y = baiduGps.latitude - 0.006;
double z = sqrt(x * x + y * y) - 0.00002 * sin(y * x_pi);
double theta = atan2(y, x) - 0.000003 * cos(x * x_pi);
CLLocationCoordinate2D googleGps;
googleGps.longitude = z * cos(theta);
googleGps.latitude = z * sin(theta);
return googleGps;
}
兩組公式的結構完全對稱,只是常數的正負號相反——這正是「互為反轉」的數學必然,也是最容易打錯字的地方。
- (void)SetMapPoint:(CLLocationCoordinate2D)myLocation
MKMapView:(MKMapView *)mapView {
MKCoordinateRegion region = { {0.0, 0.0}, {0.0, 0.0} };
region.center = myLocation;
mapView.zoomEnabled = YES;
mapView.scrollEnabled = YES;
region.span.longitudeDelta = 0.01f;
region.span.latitudeDelta = 0.01f;
[mapView setRegion:region animated:YES];
}
// 需要放註解時
- (void)SetPurchaseMapPoint:(CLLocationCoordinate2D)myLocation
MKMapView:(MKMapView *)mapView {
POI *poi = [[POI alloc] initWithCoords:myLocation];
[mapView addAnnotation:poi];
// ... 同上設定 region
}