import UIKit

//1.导入框架
import MapKit

class ViewController: UIViewController {
    lazy var geoCoder : CLGeocoder = {
        return CLGeocoder()
    }()

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        geoCoder.geocodeAddressString("广州") { (pls, err) in
            //广州坐标
            guard let gzPL = pls?.first else{
                return
            }
            
            self.geoCoder.geocodeAddressString("上海", completionHandler: { (pls, err) in
                //上海坐标
                if let shPL = pls?.first{
                    self.beginNav(startPLCL: gzPL, endPLCL: shPL)
                }
            })
        }
    }
}

// MARK: - 导航起点和终点
extension ViewController{
    func beginNav(startPLCL: CLPlacemark, endPLCL: CLPlacemark) {
        
        // 起点
        let plMK: MKPlacemark = MKPlacemark(placemark: startPLCL)
        let startItem: MKMapItem = MKMapItem(placemark: plMK)
        
        // 终点
        let endplMK: MKPlacemark = MKPlacemark(placemark: endPLCL)
        let endItem: MKMapItem = MKMapItem(placemark: endplMK)
        
        // 起点和终点
        let mapItems: [MKMapItem] = [startItem, endItem]
        
        // 导航设置字典
        let dic: [String : Any] = [
            // 导航模式
            MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving,
            // 地图样式
            MKLaunchOptionsMapTypeKey: MKMapType.standard.rawValue,
            // 显示交通
            MKLaunchOptionsShowsTrafficKey: true
        ]
        MKMapItem.openMaps(with: mapItems, launchOptions: dic)
    }
}

  



 

posted on 2018-12-13 11:04  懂事长qingzZ  阅读(259)  评论(0编辑  收藏  举报