美文网首页
swift 实现应用外导航(swift3.1)

swift 实现应用外导航(swift3.1)

作者: SamuelSeed | 来源:发表于2017-05-03 10:03 被阅读628次

    简单介绍下如何使用 swift 实现跳转到高德地图、百度地图、或系统自带地图导航,有了这个,妈妈再也不用担心app里需要实现导航功能啦😆😆😆 总结一下,高德地图跳转完直接开始导航,个人认为体验最好。百度地图需要用户手动确认一下,也还不错。自带地图加载略慢,😳😳

    //swift3.1
    let alertController = UIAlertController(title: "选择导航地图", message: nil, preferredStyle: .actionSheet)
    let cancelAction = UIAlertAction.init(title: "取消", style: .cancel) { (action) in
        
    }
    //系统自带地图,内核高德地图,无需判断是否安装
    let appleAction = UIAlertAction(title: "自带地图", style: .default){ (action) in
        let currentLocation = MKMapItem.forCurrentLocation()
        let toLocation = MKMapItem.init(placemark: MKPlacemark.init(coordinate: view.annotation.coordinate, addressDictionary: nil))
        MKMapItem.openMaps(with: [currentLocation, toLocation],
                           launchOptions: [MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving,
                                           MKLaunchOptionsShowsTrafficKey:true])
    }
    //百度地图
    if UIApplication.shared.canOpenURL(URL.init(string: "baidumap://")!) {//判断是否安装了地图
        let baiduAction = UIAlertAction(title: "百度地图", style: .default){ (action) in
            //注意:origin={{我的位置}}不要变;目的地随便写
            let urlString = "baidumap://map/direction?origin={{我的位置}}&destination=latlng:\(view.annotation.coordinate.latitude),\(view.annotation.coordinate.longitude)|name=目的地&mode=driving&coord_type=gcj02"
            let escapedString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
            UIApplication.shared.openURL(URL.init(string: escapedString!)!)
        }
        alertController.addAction(baiduAction)
    }
    //高德地图
    if UIApplication.shared.canOpenURL(URL.init(string: "iosamap://")!) {
        let gaodeAction = UIAlertAction(title: "高德地图", style: .default){ (action) in
            let urlString = "iosamap://navi?sourceApplication=随便写&backScheme=随便写&lat=\(view.annotation.coordinate.latitude)&lon=\(view.annotation.coordinate.longitude)&dev=0&style=2"
            let escapedString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
            UIApplication.shared.openURL(URL.init(string: escapedString!)!)
        }
        alertController.addAction(gaodeAction)
    }
    
    alertController.addAction(cancelAction)
    alertController.addAction(appleAction)
    
    present(alertController, animated: true, completion: nil)
    

    info.plist中需要添加高德地图、百度地图为白名单:
    在key:LSApplicationQueriesSchemes的array中增加下面两项:


    白名单配置

    相关文章

      网友评论

          本文标题:swift 实现应用外导航(swift3.1)

          本文链接:https://www.haomeiwen.com/subject/jtrktxtx.html