iOS跳转三方地图(Swift)

本文介绍了如何在iOS应用中使用MapNavigator视图,通过CLLocationCoordinate2D实例实现从起点到终点的导航,支持百度地图、高德地图、苹果地图和谷歌地图的选择。展示了在不同系统版本上的适配和相应URL scheme的配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

MapNavigator (View)

class MapNavigator: UIView,UIAlertViewDelegate  {
    let toLocation: CLLocationCoordinate2D = CLLocationCoordinate2D.init()
    let APP_NAME = "BaiDuStudy"
    let URL_SCHEME = "lgwmapnav://"
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func mapNavigatorWithEndLocation(endLocation:CLLocationCoordinate2D, andViewController superVC:UIViewController) {
       let x_pi = 3.14159265358979324 * 3000.0 / 180.0
       var x = endLocation.longitude - 0.0065, y = endLocation.latitude - 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)
        var end = endLocation
        end.longitude = z * cos(theta)
        end.latitude = z * sin(theta)
        let urlScheme = URL_SCHEME
        let appName = APP_NAME
        
        let coordinate = end
        if (Float(UIDevice.current.systemVersion)! > 8.0) {  // ios8以上系统
            let alert = UIAlertController.init(title: "选择地图", message: nil, preferredStyle: UIAlertController.Style.actionSheet)
            
            if UIApplication.shared.canOpenURL(URL.init(string: "baidumap://")!) {
                let action  = UIKit.UIAlertAction.init(title: "百度地图", style: .default) { (action) in
                    let urlString = NSString.init(format: "baidumap://map/direction?origin={{我的位置}}&destination=latlng:%f,%f|name=目的地&mode=driving&coord_type=gcj02",coordinate.latitude, coordinate.longitude).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
                    UIApplication.shared.open(URL.init(string: urlString!)!)
                }
                alert.addAction(action)
            }

            if UIApplication.shared.canOpenURL(URL.init(string: "iosamap://")!) {
                print("进来了吧!!")
                let action  =  UIKit.UIAlertAction.init(title: "高德地图", style: .default) { (action) in
                    let urlString = NSString.init(format: "iosamap://navi?sourceApplication=%@&backScheme=%@&lat=%f&lon=%f&dev=0&style=2",appName,urlScheme,coordinate.latitude, coordinate.longitude).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
                    UIApplication.shared.open(URL.init(string: urlString!)!)
                }
                alert.addAction(action)
            }
            
            if UIApplication.shared.canOpenURL(URL.init(string: "http://maps.apple.com/")!) {
                let action  = UIKit.UIAlertAction.init(title: "苹果地图", style: .default) { (action) in
                    let currentLocation = MKMapItem.forCurrentLocation()
                    let toLocation = MKMapItem.init(placemark: MKPlacemark.init(coordinate: coordinate))
                    MKMapItem.openMaps(with: [currentLocation, toLocation],
                                       launchOptions:[
                                        MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving,
                                        MKLaunchOptionsShowsTrafficKey: NSNumber.init(value: true)])
                }
                alert.addAction(action)
            }
            
            if UIApplication.shared.canOpenURL(URL.init(string: "comgooglemaps://")!) {
                let action  =  UIKit.UIAlertAction.init(title: "谷歌地图", style: .default) { (action) in
                    let urlString = NSString.init(format: "comgooglemaps://?x-source=%@&x-success=%@&saddr=&daddr=%f,%f&directionsmode=driving",appName,urlScheme,coordinate.latitude, coordinate.longitude).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
                    UIApplication.shared.open(URL.init(string: urlString!)!)
                }
                alert.addAction(action)
            }
            let action = UIKit.UIAlertAction.init(title: "取消", style: .cancel)
            alert.addAction(action)
            superVC.present(alert, animated: true, completion: {
                
            })
        }
    }
        
    
    func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int){
        let urlScheme = URL_SCHEME
        let appName = APP_NAME
        let coordinate = self.toLocation
        let buttonTitleStr = alertView.buttonTitle(at: buttonIndex)
        //选中的是取消
        if (buttonIndex == alertView.cancelButtonIndex) {
            return;
        }
        if (buttonTitleStr == "苹果地图") { // 苹果地图
            let currentLocation = MKMapItem.forCurrentLocation()
            let toLocation = MKMapItem.init(placemark: MKPlacemark.init(coordinate: coordinate))
            MKMapItem.openMaps(with: [currentLocation, toLocation],
                               launchOptions:[
                                MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving,
                                MKLaunchOptionsShowsTrafficKey: NSNumber.init(value: true)])
        }else if (buttonTitleStr == "百度地图"){ // 百度地图
            let urlString = NSString.init(format: "baidumap://map/direction?origin={{我的位置}}&destination=latlng:%f,%f|name=目的地&mode=driving&coord_type=gcj02",coordinate.latitude, coordinate.longitude).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
            UIApplication.shared.open(URL.init(string: urlString! )!)

        }else if (buttonTitleStr == "高德地图"){ // 高德地图
            let urlString = NSString.init(format: "iosamap://navi?sourceApplication=%@&backScheme=%@&lat=%f&lon=%f&dev=0&style=2",appName,urlScheme,coordinate.latitude, coordinate.longitude).addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
            UIApplication.shared.open(URL.init(string: urlString!)!)
            

        }else if (buttonTitleStr == "谷歌地图"){ //谷歌地图
            let urlString = NSString.init(format: "comgooglemaps://?x-source=%@&x-success=%@&saddr=&daddr=%f,%f&directionsmode=driving",appName,urlScheme,coordinate.latitude