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

iOS 定位不做會偏:徹底搞懂 WGS-84 與 GCJ-02 座標系

編輯:iOS 開發基礎

為什麼一定要「糾偏」?

先說結論:手機 GPS 回傳的原始經緯度,在中國境內是沒辦法直接貼到在地圖上使用的,因為兩套座標系之間被刻意插入了一段隨機偏差。

GCJ-02 是由國家測繪主管部門制訂的地理資訊系統座標系統,本質上是一套對經緯度做加密的演算法——在真實數值上疊加一段隨機偏移。境內公開發布的各類地圖服務(包含電子地圖),都必須至少採用 GCJ-02 對地理位置進行一次加密。

拆開來看就很清楚了:

  • WGS-84:GPS 定位直接得到的真實經緯度,國際通用標準。
  • GCJ-02:在 WGS-84 基礎上加密後的座標系,社群裡常叫它「火星座標」。它的偏差是隨機且非線性的,無法用簡單的線性公式還原。

所以,拿 Core Location 給的原始座標去餵給國內的地圖服務,結果必然是偏的。

最省事的做法:借系統地圖拿 GCJ-02

網路上流傳的各種「座標反加密演算法」我實際測過,效果並不理想——偏移依然存在,只是換了個方向偏而已。與其自己硬算,不如直接借用 iOS 自帶的地圖定位能力:MKMapView 回報的 userLocation,本身已經是 GCJ-02 座標系下的結果。

第一步:在 Info.plist 中宣告定位用途

需要加入以下 Key:

// 允許 App 在執行期間定位
Privacy - Location When In Use Usage Description

// 允許 App 全程定位
Privacy - Location Always Usage Description

Value 要多留意:若要相容 iOS 10,Value 必須非空,否則 App 會直接 crash;只支援 iOS 8–9 時才允許留空。

第二步:引入框架並宣告屬性

#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>

@interface LocationViewController () <MKMapViewDelegate, CLLocationManagerDelegate>
{
    MKMapView *_mapView;   // 全域地圖物件
}

// 定位服務入口,設為屬性以免被提前釋放
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, copy)   NSString *latitude;   // 緯度
@property (nonatomic, copy)   NSString *longitude;  // 經度
@end

第三步:初始化定位服務與地圖

- (void)viewDidLoad {
    [super viewDidLoad];

    // 先判斷定位服務是否開啟、GPS 感測器是否可用
    if ([CLLocationManager locationServicesEnabled]) {
        if ([CLLocationManager headingAvailable]) {
            self.locationManager = [[CLLocationManager alloc] init];
            self.locationManager.delegate = self;
            self.locationManager.desiredAccuracy = kCLLocationAccuracyBest; // 最高精度
            self.locationManager.headingFilter = kCLHeadingFilterNone;     // 關閉濾波器,接收全部更新

            // iOS 8 起需要主動向使用者請求授權
            if ([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
                [self.locationManager requestWhenInUseAuthorization];
            } else {
                NSLog(@"系統版本不匹配");
            }
        } else {
            NSLog(@"感測器不可用");
        }
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"未開啟定位服務"
                                                        message:@"請至 設定 - 隱私權 - 定位服務 中開啟"
                                                       delegate:self
                                              cancelButtonTitle:@"確定"
                                              otherButtonTitles:nil, nil];
        [alert setAlertViewStyle:UIAlertViewStyleDefault];
        [alert show];
    }

    // 初始化地圖。若只想要座標、不要畫面,可把 frame 設到視圖外或隱藏
    _mapView = [[MKMapView alloc] init];
    _mapView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height / 3);
    _mapView.delegate = self;
    _mapView.mapType = MKMapTypeStandard;          // 標準模式
    _mapView.showsUserLocation = YES;              // 顯示當前位置
    _mapView.userTrackingMode = MKUserTrackingModeFollow; // 跟隨
    [self.view addSubview:_mapView];
    // _mapView.hidden = YES;
}

第四步:控制定位的開始與結束

開始定位呼叫 startUpdatingLocation,結束定位呼叫 stopUpdatingLocation,時機由你自己決定。放在 viewWillAppear / viewWillDisappear 是最常見的選擇:

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.locationManager startUpdatingLocation];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.locationManager stopUpdatingLocation];
}

第五步:把座標反編碼成地址

系統預設點擊藍點只會顯示「當前位置」四個字。想顯示實際地址,需要設定藍點的 title;如果你根本不顯示地圖,這個代理方法可以省略。

#pragma mark - MKMapViewDelegate
- (void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
    CLGeocoder *geo = [[CLGeocoder alloc] init];
    [geo reverseGeocodeLocation:userLocation.location completionHandler:^(NSArray *placemarks, NSError *error) {
        CLPlacemark *pm = [placemarks lastObject];
        userLocation.title = pm.name;
    }];
}

第六步:取出經緯度並拼接方向

#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    // 寫法一:直接拿 CLLocation 的座標(WGS-84)
    CLLocation *location = [locations lastObject];
    CLLocationCoordinate2D coords = location.coordinate;

    // 寫法二:拿地圖上的使用者座標(GCJ-02),兩者擇一
    // CLLocationCoordinate2D coords = _mapView.userLocation.location.coordinate;

    NSLog(@"緯度 %f, 經度 %f", coords.latitude, coords.longitude);

    NSString *latitudeDirection = nil;
    NSString *longitudeDirection = nil;

    if (coords.latitude >= 0) {
        latitudeDirection = @"N";
    } else {
        latitudeDirection = @"S";
    }

    if (coords.longitude >= 0) {
        longitudeDirection = @"E";
    } else {
        longitudeDirection = @"W";
    }

    self.latitude  = [NSString stringWithFormat:@"%f%@", coords.latitude,  latitudeDirection];
    self.longitude = [NSString stringWithFormat:@"%f%@", coords.longitude, longitudeDirection];

    // 這個代理方法預設每秒觸發一次。
    // 若只需要定位成功一次,請在此處呼叫 stopUpdatingLocation 結束定位。
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    if (error.code == kCLErrorDenied) {
        // 使用者拒絕授權,在這裡提示失敗原因
    }
}

附錄:十進制經緯度轉度分秒

很多後台或對接場景需要 60 進制的度分秒格式,下面是手寫的轉換方法:

#pragma mark - 經緯度單位轉換
- (NSString *)stringWithCoordinateString:(NSString *)coordinateString {
    // 範例輸入:118.815033

    // 取出整數部分作為「度」
    int degree = [coordinateString intValue];                       // 118

    // 取出小數部分
    NSArray *array = [coordinateString componentsSeparatedByString:@"."];
    NSString *decimalPart = [array lastObject];

    // 拼成 0.xxxx 形式並轉為 float
    NSString *str1 = [NSString stringWithFormat:@"0.%@", decimalPart];
    float minuteFloat = [str1 floatValue];                          // 0.815033

    // 小數部分乘 60 得到「分」
    float minuteTotal = minuteFloat * 60;                           // 48.90198
    NSString *minuteStr = [NSString stringWithFormat:@"%f", minuteTotal];
    int minute = [minuteStr intValue];                              // 48

    // 再把「分」的小數部分乘 60 得到「秒」
    NSArray *secondArr = [minuteStr componentsSeparatedByString:@"."];
    NSString *lastPart = [secondArr lastObject];
    NSString *str2 = [NSString stringWithFormat:@"0.%@", lastPart];
    float secondFloat = [str2 floatValue];                          // 0.90198
    float secondTotal = secondFloat * 60;                           // 54.1188
    NSString *secondStr = [NSString stringWithFormat:@"%f", secondTotal];
    int second = [secondStr intValue];                              // 54

    return [NSString stringWithFormat:@"%d°%d'%d''", degree, minute, second];
}

掌握「系統地圖回報的就是 GCJ-02」這個前提之後,糾偏問題其實不需要任何複雜演算法,只要選對資料來源即可。

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