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

iOS GPS 定位與座標轉換:手機座標、火星座標、百度座標三方互轉

編輯:iOS 開發綜合

做地圖相關功能時,最容易被忽略的細節是座標系不一致。手機 GPS 給出的是 WGS-84,而 Google 地圖用的是 GCJ-02(俗稱火星座標),百度又自有一套 BD-09。混用而不轉換,結果就是定位點偏移幾百公尺。以下把整個流程整理成一個可重用的公共類別。

GPScombineClass 的職責

這個類別負責四件事:啟動定位、取得 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
}

幾個必須修正的地方

  • iOS 8 之後需要主動請求權限:要在 Info.plist 加入 NSLocationWhenInUseUsageDescription,並呼叫 requestWhenInUseAuthorization,否則不會跳出同意框,定位永遠失敗。
  • 不建议用 addSubview 直接操作 window 上的 view,也應避免把 MKMapView 的屬性寫成 setZoomEnabled: 這類舊式呼叫,改用點語法即可。
  • SQL 用字串拼接雖是內部整數,仍建議改用參數綁定,養成習慣。
  • delegate 方法已更名:locationManager:didUpdateToLocation:fromLocation: 已被 locationManager:didUpdateLocations: 取代,新專案請用後者。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved