您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 教學 >> iOS 相關教學

iOS 定位實作與座標轉換:GPS、火星座標與百度座標的互轉

編輯:iOS 相關教學

只要 App 裡有用到地圖,就一定會遇到座標系問題:手機 GPS 回傳的是 WGS-84,但國內地圖服務用的是偏移過的座標,直接拿 GPS 值去放標記會產生明顯位移。本文先談定位與反查地址,再說明座標轉換的實作。

一、定位與位置資訊反查

需要引入兩個框架:CoreLocation.framework 負責取得座標,MapKit.framework 負責反查地址。

AppDelegate.h

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

@interface AppDelegate : UIResponder <UIApplicationDelegate, CLLocationManagerDelegate>
@property (strong, nonatomic) UIWindow *window;
@end

啟動定位

- (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];
    [self.window addSubview:button];

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 150, 320, 30)];
    label.tag = 101;
    label.text = @"等待定位中....";
    [self.window addSubview:label];

    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.0 以上
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    CLLocation *newLocation = locations[0];
    CLLocationCoordinate2D oldCoordinate = newLocation.coordinate;
    NSLog(@"舊的經度:%f,舊的緯度:%f", oldCoordinate.longitude, oldCoordinate.latitude);

    [manager stopUpdatingLocation];

    // ---- 位置反編碼(iOS 5.0 之後)----
    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);               // 國家
        }
    }];
}

二、GPS 座標轉火星座標

這裡把定位與轉換整理成一個 GPScombineClass 公共類,對外提供「在地圖上標出自己的位置」的介面。

GPScombineClass.h

#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

GPScombineClass.m

#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 → 火星(Google)座標:以離散步表查表做偏移修正
-(CLLocationCoordinate2D)zzTransGPS:(CLLocationCoordinate2D)yGps {
    int TenLat = (int)(yGps.latitude * 10);
    int TenLog = (int)(yGps.longitude * 10);
    NSString *sql = [[NSString alloc] initWithFormat:
        @"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  = 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)setMyMapPonitByMKMapView:(MKMapView *)MyMap {
    [self SetMapPoint:deleeverLocation MKMapView:MyMap];
    MyMap = mainMapView;
}

-(void)SetMapPoint:(CLLocationCoordinate2D)myLocation MKMapView:(MKMapView *)mapView {
    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];
}

// 顯示商品資訊(百度座標 → 轉回火星座標後放標記)
-(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];
}

三、實務上的幾點提醒

  • iOS 8 之後必須先呼叫 requestWhenInUseAuthorization 取得使用者授權,並在 Info.plist 加上 NSLocationWhenInUseUsageDescription(iOS 11 起建議用 NSLocationAlwaysAndWhenInUseUsageDescription),否則不會收到任何回呼。
  • zzTransGPS: 用的是離散步表查表法,精度受限於表格密度;若追求精準,建議改用開源的 eviltransform 等演算法實作。
  • 示意程式中的 sqlite3_stmt 記得在讀取後 sqlite3_finalize,避免 statement 洩漏。
  • 示意程式中的 MRC 寫法(如 [label release])在 ARC 專案下需移除。
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved