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
    }
}

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

啊啊,祝大家十一快乐

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,607评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,047评论 2 379
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,496评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,405评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,400评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,479评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,883评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,535评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,743评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,544评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,612评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,309评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,881评论 3 306
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,891评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,136评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,783评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,316评论 2 342

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,363评论 25 707
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,010评论 4 62
  • 做梦,几乎是我这一生的每个夜晚都在做的事情,不但做梦,而且不止一个梦,通常每个晚上要做2-4个梦,有时是独立的,有...
    张德祥阅读 144评论 0 0
  • 出30:19亚伦和他的儿子要在这盆里洗手洗脚。 出30:20他们进会幕,或是就近坛前供职,给耶和华献火祭的时候,必...
    宁宁2018阅读 197评论 0 0
  • 人生,就是一场较量, 活着,就是一份证明, 每个人都有自己的难处, 脸上的笑容太少, 心里的孤独太多, 身上的压力...
    大师贴膜小叶子阅读 222评论 0 1