swift -> 获取经纬度

首先是通过 系统 CoreLocation 获取GPS模块原始的 坐标经纬度。

参考: http://www.hangge.com/blog/cache/detail_783.html

import UIKit
import CoreLocation

class MyLocation: UIViewController,CLLocationManagerDelegate{
    
    let locationMana:CLLocationManager = CLLocationManager();
    
    override func viewDidLoad() {
        super.viewDidLoad();
        // Do any additional setup after loading the view.
        //设置定位服务管理器代理
        locationMana.delegate = self
        //设置定位进度
        locationMana.desiredAccuracy = kCLLocationAccuracyBest
 
        if (CLLocationManager.locationServicesEnabled())
        {
            //允许使用定位服务的话,开启定位服务更新
            locationMana.startUpdatingLocation();
            print("定位开始")
        }
    }   
      //定位改变执行,可以得到新位置、旧位置
    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        //获取最新的坐标
        let currLocation:CLLocation = locations.last!
        label1.text = "经度:\(currLocation.coordinate.longitude)"
        //获取纬度
        label2.text = "纬度:\(currLocation.coordinate.latitude)"
        //获取海拔
        label3.text = "海拔:\(currLocation.altitude)"
        //获取水平精度
        label4.text = "水平精度:\(currLocation.horizontalAccuracy)"
        //获取垂直精度
        label5.text = "垂直精度:\(currLocation.verticalAccuracy)"
        //获取方向
        label6.text = "方向:\(currLocation.course)"
        //获取速度
        label7.text = "速度:\(currLocation.speed)"
    }
        
}

 其中:

1,定位精度的设置
定位服务管理类CLLocationManager的desiredAccuracy属性表示精准度,有如下6种选择:

kCLLocationAccuracyBestForNavigation :精度最高,一般用于导航
kCLLocationAccuracyBest : 精确度最佳
kCLLocationAccuracyNearestTenMeters :精确度10m以内
kCLLocationAccuracyHundredMeters :精确度100m以内
kCLLocationAccuracyKilometer :精确度1000m以内
kCLLocationAccuracyThreeKilometers :精确度3000m以内

以上 是 获取 GPS 原始的 经纬度, 但是与 准确真实的 经纬度有偏差, 3个名词:

地球坐标 = 以上获取到的原始GPS 经纬度

火星坐标 = 中国国情偏移量计算结果

百度坐标 = 百度地图的坐标

下面 两种方法 将 地球坐标 转 百度坐标,

一,  通过外部库 TQLocationConverter  库文件 见附件 

在获取到 地球坐标后 开始 转换

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    //获取最新的坐标

    let currLocation:CLLocation = locations.last!

    

    var locl:CLLocationCoordinate2D = CLLocationCoordinate2DMake(currLocation.coordinate.latitude,currLocation.coordinate.longitude);

    // 地球坐标 火星坐标

    locl = TQLocationConverter.transformFromWGSToGCJ(locl);

    // 火星坐标 百度坐标

    locl = TQLocationConverter.transformFromGCJToBaidu(locl);

    print("\(locl.longitude),\(locl.latitude)");

    

}

二, 通过 百度提供接口

http://api.map.baidu.com/ag/coord/convert?x=105.384517616982&y=30.8762459390228&from=0&to=4&mode=1

其中 X,Y 是经纬度,  from和to表示坐标系,0表示地球坐标,2表示火星坐标,4表示百度坐标

结果 是个 base64 encode 串

[{"error":0,"x":"MTA1LjM5NDcyMjc0MjM2","y":"MzAuODgwMDEyNjQwMzg3"}]

然后自己decode

两种方式, 百度 的 还是 稍微要 准一点点

猜你喜欢

转载自mft.iteye.com/blog/2310507
今日推荐