swift MKMapView 定位,加大头针,跳转高德等三方地图,地球坐标,火星坐标,百度坐标转换

swift 撸了个简单地图,实现的主要功能就是标题了,废话懒的多说,代码说话

//
//  MapController.swift
//  sendWater
//
//  Created by 孟祥锟 on 2018/9/28.
//  Copyright © 2018年 sandianshui. All rights reserved.
//

import UIKit

import MapKit
import CoreLocation


private let annotationId : String = "annotationId"

class MapController: UIViewController {
    //前面页面传进来的地理位置
    var locationStr = ""
    var coord2D:CLLocationCoordinate2D?
    
    //MARK:--懒加载
    private lazy var mapV : MKMapView = {[weak self] in
        let mapV                 = MKMapView()
        mapV.mapType             = MKMapType.standard
        mapV.userTrackingMode    = MKUserTrackingMode.followWithHeading
        mapV.showsUserLocation   = true
        mapV.delegate            = self
        
        return mapV
    }()
    private lazy var locationManager : CLLocationManager = {[weak self] in
        let manager = CLLocationManager()
        //设置定位精度
        manager.desiredAccuracy = kCLLocationAccuracyBest
        manager.distanceFilter  = 100.0
        manager.delegate        = self
        manager.requestWhenInUseAuthorization()
        return manager
    }()
    //根据地址名字获取经纬度用
    private lazy var geocoder : CLGeocoder = {
        let geocoder = CLGeocoder()
        return geocoder
    }()
    private lazy var annotation : MKAnnotationView = {
        let annot       = MKPointAnnotation()
        let annotationV = MKAnnotationView(annotation:annot, reuseIdentifier: annotationId)
        return annotationV
    }()
    
    
    private lazy var backBtn : UIButton = { [weak self] in
        let backBtn                     = UIButton(type: UIButtonType.custom)
        backBtn.backgroundColor         = UIColor.white
        backBtn.setImage(UIImage(named: "backImg"), for: .normal)
        backBtn.imageEdgeInsets         = UIEdgeInsets(top: 6, left: 10, bottom: 6, right: 10)
        backBtn.imageView?.contentMode  = .scaleAspectFit
        backBtn.clipsToBounds           = true
        backBtn.layer.cornerRadius      = 4
        backBtn.addTarget(self, action: #selector(backUpPage), for: .touchUpInside)
        return backBtn
    }()
    private lazy var locationBtn : UIButton = { [weak self] in
        let locationBtn               = UIButton(type: UIButtonType.custom)
        locationBtn.setBackgroundImage(UIImage(named: "locationBtn"), for: .normal)
        locationBtn.addTarget(self, action: #selector(locationSelf), for: .touchUpInside)
        return locationBtn
    }()
    private lazy var gpsBtn : UIButton = {
        let gpsBtn = UIButton(type: UIButtonType.custom)
        gpsBtn.backgroundColor = UIColor.white
        gpsBtn.setTitle("导 航", for: .normal)
        gpsBtn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        gpsBtn.setTitleColor(UIColor.black, for: .normal)
        gpsBtn.addTarget(self, action: #selector(gpsBtnPress), for: .touchUpInside)
        return gpsBtn
    }()
    private lazy var alertSheet : UIAlertController = {
         let alertSheet = UIAlertController(title: "导航", message: "", preferredStyle: UIAlertControllerStyle.actionSheet)
        return alertSheet
    }()
    //MARK:--入口函数
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        //进行反地理编码
        geocodeingGetLocation()
        //设置底部弹框
        setAlertSheet()
    }
    //页面一显示就进行定位
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    
}
//MARK:--设置UI
extension MapController {
    private func setUI () {
        view.addSubview(mapV)
        view.addSubview(backBtn)
        view.addSubview(gpsBtn)
        view.addSubview(locationBtn)
        
        mapV.snp.makeConstraints { (make) in
            make.edges.equalTo(self.view)
        }
        
        backBtn.snp.makeConstraints { (make) in
            make.left.equalTo(self.view).offset(15)
            make.top.equalTo(self.view).offset(30)
            make.width.equalTo(35)
            make.height.equalTo(30)
        }
        
        gpsBtn.snp.makeConstraints { (make) in
            make.left.bottom.right.equalTo(self.view)
            make.height.equalTo(60)
        }
        
        locationBtn.snp.makeConstraints { (make) in
            make.left.equalTo(self.view).offset(15)
            make.bottom.equalTo(self.gpsBtn.snp.top).offset(-25)
            make.width.height.equalTo(35)
        }
    }
    //设置底部弹框
    private func setAlertSheet () {
        
        let sheetOptionZero      = UIAlertAction(title: "自带地图", style: UIAlertActionStyle.default) { (action) in
            
            let currentLocation  = MKMapItem.forCurrentLocation()
            let toLocation = MKMapItem.init(placemark: MKPlacemark.init(coordinate: self.coord2D!, addressDictionary: nil))
            MKMapItem.openMaps(with: [currentLocation, toLocation],
                               launchOptions: [MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving,
                                               MKLaunchOptionsShowsTrafficKey:true])
    
            self.alertSheet.dismiss(animated: true, completion: nil)
            
            
        }
        
        let sheetOptionO          = UIAlertAction(title: "高德地图", style: UIAlertActionStyle.default) { (action) in
            
            
            if UIApplication.shared.canOpenURL(URL.init(string: "iosamap://")!) {
                let urlString     = "iosamap://navi?sourceApplication=随便写&backScheme=随便写&lat=\(self.coord2D!.latitude)&lon=\(self.coord2D!.longitude)&dev=0&style=2"
                let escapedString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
                UIApplication.shared.openURL(URL.init(string: escapedString!)!)
            }else{
                ModelSelector.showMessage(message: "您没有安装高德地图")
            }
            
            self.alertSheet.dismiss(animated: true, completion: nil)
            
        }
        
        let sheetOptionT       = UIAlertAction(title: "百度地图", style: UIAlertActionStyle.default) { (action) in
            
            if UIApplication.shared.canOpenURL(URL.init(string: "baidumap://")!) {
            //注意:origin={{我的位置}}不要变;目的地随便写
            let urlString     = "baidumap://map/direction?origin={{我的位置}}&destination=latlng:\(self.coord2D!.latitude),\(self.coord2D!.longitude)|name=\(self.locationStr)&mode=driving&coord_type=gcj02"
            let escapedString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
            UIApplication.shared.openURL(URL.init(string: escapedString!)!)
                
            }else{
                ModelSelector.showMessage(message: "您没有安装百度地图")
            }
            
            self.alertSheet.dismiss(animated: true, completion: nil)
            
        }
        let sheetOptionHidden  = UIAlertAction(title: "取消", style: UIAlertActionStyle.default) { (action) in
            
            self.alertSheet.dismiss(animated: true, completion: nil)
            
        }
        
        alertSheet.addAction(sheetOptionZero)
        alertSheet.addAction(sheetOptionO)
        alertSheet.addAction(sheetOptionT)
        alertSheet.addAction(sheetOptionHidden)

    }
}
//MARK:--事件处理
extension MapController {
    //返回上一页
    @objc private func backUpPage () {
        self.dismiss(animated: true, completion: nil)
    }
    //点击定位
    @objc private func locationSelf () {
       locationManager.startUpdatingLocation()
    }
    //点击导航
    @objc private func gpsBtnPress () {
        self.present(alertSheet, animated: true, completion: nil)
    }
    //理编码操作
    private func  geocodeingGetLocation () {
        geocoder.geocodeAddressString(self.locationStr) { (placeMarks, error) in
            if error != nil {
               ModelSelector.showMessage(message: "没找到您要的地址")
            }else{
                
                guard let placeM : CLPlacemark = (placeMarks?.first) else { return }
                guard let locat                = placeM.location else { return }
                
                let center               = locat.coordinate
                let span                 = MKCoordinateSpanMake(0.01, 0.01)
                let region               = MKCoordinateRegionMake(center, span)
                self.mapV.setRegion(region, animated: true)
                //讲coord2D 赋值给全局变量,调第三方的时候使用
                self.coord2D             = center
                
                let annot                = MyAnnotation()
                annot.coordinate         = center
                annot.title              = self.locationStr
                self.mapV.addAnnotation(annot)
            }
        }
    }
    
}

extension MapController : MKMapViewDelegate {
     //更新到用户的位置时就会调用(显示的位置、显示范围改变) 实时更新
    func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
       
    }
    
    func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
        
        
        if !(annotation is MyAnnotation) {
            return nil
        }
        
        var annotV   = mapView.dequeueReusableAnnotationView(withIdentifier: annotationId)
        
        if annotV    == nil {
            annotV   = MKAnnotationView(annotation: annotation, reuseIdentifier: annotationId)
        }
        annotV?.annotation         = annotation
        annotV?.image              = UIImage(named: "address")
        annotV?.contentMode        = .scaleToFill
        annotV?.canShowCallout     = true//设置大头针弹框
        annotV?.calloutOffset      = CGPoint(x: 10, y: 0)
       
        return annotV
    }
}

extension MapController : CLLocationManagerDelegate {
    //点击定位走一次
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        //地球坐标转化成火星坐标
        guard let location   = locations.first?.locationMarsFromEarth() else { return }
        let  center          = location.coordinate
        let  span            = MKCoordinateSpanMake(0.01, 0.01)
        let  region          = MKCoordinateRegionMake(center, span)
        self.mapV.setRegion(region, animated: true)
        self.locationManager.stopUpdatingLocation()
    }
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error)
    }
}

上面是我写的代码,下面坐标转换当然网上找的了,附上https://www.jianshu.com/p/347e4dc3d05a ,万分感谢倾世圣伊的分享,简单来说就是对CLLocation 做了个扩展。下面附上他的代码。

import UIKit
import CoreLocation

// --- transform_earth_from_mars ---
// 参考来源:https://on4wp7.codeplex.com/SourceControl/changeset/view/21483#353936
// Krasovsky 1940
//
// a = 6378245.0, 1/f = 298.3
// b = a * (1 - f)
// ee = (a^2 - b^2) / a^2;
let a:Double = 6378245.0
let ee:Double = 0.00669342162296594323

// --- transform_earth_from_mars end ---
// --- transform_mars_vs_bear_paw ---
// 参考来源:http://blog.woodbunny.com/post-68.html
let x_pi:Double = M_PI * 3000.0 / 180.0

public extension CLLocation {
    
    /// 从地图坐标转化到火星坐标
    ///
    /// - Returns: CLLocation
    func locationMarsFromEarth() -> CLLocation {
        
        let (n_lat,n_lng) = CLLocation.transform_earth_from_mars(lat: self.coordinate.latitude, lng: self.coordinate.longitude)
        let coord_2d = CLLocationCoordinate2D(latitude: n_lat + self.coordinate.latitude, longitude: n_lng + self.coordinate.longitude)
        
        return CLLocation(coordinate: coord_2d, altitude: self.altitude, horizontalAccuracy: self.horizontalAccuracy, verticalAccuracy: self.horizontalAccuracy, course: self.course, speed: self.speed, timestamp: self.timestamp)
    }
    
    /// 从火星坐标到地图坐标
    ///
    /// - Returns: CLLocation
    func locationEarthFromMars() -> CLLocation {
        
        let (n_lat,n_lng) = CLLocation.transform_earth_from_mars(lat: self.coordinate.latitude, lng: self.coordinate.longitude)
        let coord_2d = CLLocationCoordinate2D(latitude: self.coordinate.latitude - n_lat, longitude: self.coordinate.longitude - n_lng)
        
        return CLLocation(coordinate: coord_2d, altitude: self.altitude, horizontalAccuracy: self.horizontalAccuracy, verticalAccuracy: self.horizontalAccuracy, course: self.course, speed: self.speed, timestamp: self.timestamp)
    }
    
    /// 从火星坐标转化到百度坐标
    ///
    /// - Returns: CLLocation
    func locationBaiduFromMars() -> CLLocation {
        
        let (n_lat,n_lng) = CLLocation.transform_mars_from_baidu(lat: self.coordinate.latitude, lng: self.coordinate.longitude)
        let coord_2d = CLLocationCoordinate2D(latitude: n_lat, longitude: n_lng)
        
        return CLLocation(coordinate: coord_2d, altitude: self.altitude, horizontalAccuracy: self.horizontalAccuracy, verticalAccuracy: self.horizontalAccuracy, course: self.course, speed: self.speed, timestamp: self.timestamp)
    }
    
    /// 从百度坐标到火星坐标
    ///
    /// - Returns: CLLocation
    func locationMarsFromBaidu() -> CLLocation {
        let (n_lat,n_lng) = CLLocation.transform_baidu_from_mars(lat: self.coordinate.latitude, lng: self.coordinate.longitude)
        let coord_2d = CLLocationCoordinate2D(latitude: n_lat, longitude: n_lng)
        
        return CLLocation(coordinate: coord_2d, altitude: self.altitude, horizontalAccuracy: self.horizontalAccuracy, verticalAccuracy: self.horizontalAccuracy, course: self.course, speed: self.speed, timestamp: self.timestamp)
        
    }
    
    /// 从百度坐标到地图坐标
    ///
    /// - Returns: CLLocation
    func locationEarthFromBaidu() -> CLLocation {
        
        let mars = self.locationMarsFromBaidu()
        let (n_lat,n_lng) = CLLocation.transform_earth_from_mars(lat: mars.coordinate.latitude, lng: mars.coordinate.longitude)
        let coord_2d = CLLocationCoordinate2D(latitude: self.coordinate.latitude - n_lat, longitude: self.coordinate.longitude - n_lng)
        
        return CLLocation(coordinate: coord_2d, altitude: self.altitude, horizontalAccuracy: self.horizontalAccuracy, verticalAccuracy: self.horizontalAccuracy, course: self.course, speed: self.speed, timestamp: self.timestamp)
    }
    
    private class func transform_earth_from_mars(lat: Double, lng: Double) -> (Double, Double) {
        if CLLocation.transform_sino_out_china(lat: lat, lng: lng) {
            return (lat, lng)
        }
        var dLat = CLLocation.transform_earth_from_mars_lat(lng - 105.0, lat - 35.0)
        var dLng = CLLocation.transform_earth_from_mars_lng(lng - 105.0, lat - 35.0)
        let radLat = lat / 180.0 * M_PI
        var magic = sin(radLat)
        magic = 1 - ee * magic * magic
        let sqrtMagic:Double = sqrt(magic)
        dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * M_PI)
        dLng = (dLng * 180.0) / (a / sqrtMagic * cos(radLat) * M_PI)
        return (dLat,dLng)
    }
    private class func transform_earth_from_mars_lat(_ x: Double,_ y: Double) -> Double {
        var ret: Double = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * sqrt(fabs(x))
        ret += (20.0 * sin(6.0 * x * M_PI) + 20.0 * sin(2.0 * x * M_PI)) * 2.0 / 3.0
        ret += (20.0 * sin(y * M_PI) + 40.0 * sin(y / 3.0 * M_PI)) * 2.0 / 3.0
        ret += (160.0 * sin(y / 12.0 * M_PI) + 320 * sin(y * M_PI / 30.0)) * 2.0 / 3.0
        return ret
    }
    private class func transform_earth_from_mars_lng(_ x: Double,_ y: Double) -> Double {
        var ret: Double = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * sqrt(fabs(x))
        ret += (20.0 * sin(6.0 * x * M_PI) + 20.0 * sin(2.0 * x * M_PI)) * 2.0 / 3.0
        ret += (20.0 * sin(x * M_PI) + 40.0 * sin(x / 3.0 * M_PI)) * 2.0 / 3.0
        ret += (150.0 * sin(x / 12.0 * M_PI) + 300.0 * sin(x / 30.0 * M_PI)) * 2.0 / 3.0
        return ret
    }
    private class func transform_mars_from_baidu(lat: Double, lng: Double) -> (Double,Double) {
        let x = lng , y = lat
        let z = sqrt(x * x + y * y) + 0.00002 * sin(y * x_pi)
        let theta = atan2(y, x) + 0.000003 * cos(x * x_pi)
        return (z * sin(theta) + 0.006, z * cos(theta) + 0.0065)
    }
    private class func transform_baidu_from_mars(lat: Double, lng: Double) -> (Double,Double) {
        let x = lng - 0.0065 , y = lat - 0.006
        let z =  sqrt(x * x + y * y) - 0.00002 * sin(y * x_pi)
        let theta = atan2(y, x) - 0.000003 * cos(x * x_pi)
        return (z * sin(theta), z * cos(theta))
    }
    private class func transform_sino_out_china(lat: Double, lng: Double) -> Bool {
        if (lng < 72.004 || lng > 137.8347) {
            return true
        }
        if (lat < 0.8293 || lat > 55.8271) {
            return true
        }
        return false
    }
}

没啥事儿,就是想写个玩儿

啊啊,祝大家十一快乐

你可能感兴趣的:(swift MKMapView 定位,加大头针,跳转高德等三方地图,地球坐标,火星坐标,百度坐标转换)