高德地图路线规划线路补全

我们在使用高德地图的规划线路时,开始起点和规划线路起点有一定距离没绘制折线。下面是我使用高德地图示例代码里骑行路线规划添加补全线路的方法(步行/驾车/公交同理):


import UIKit

class RideRoutePlanViewController: UIViewController, MAMapViewDelegate, AMapNaviRideManagerDelegate, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    let routePlanInfoViewHeight: CGFloat = 100.0
    let routeIndicatorViewHeight: CGFloat = 64.0
    let collectionCellIdentifier = "kCollectionCellIdentifier"
    
    var mapView: MAMapView!
    var rideManager: AMapNaviRideManager!
    
    //-------------------------------1.添加坐标点数组属性 保存规划线路的所有关键坐标--------------------------------
    var coords: [CLLocationCoordinate2D]!
    
    //为了方便展示骑行路径规划,选择了固定的起终点
    let startPoint = AMapNaviPoint.location(withLatitude: 39.993135, longitude: 116.474175)!
    let endPoint = AMapNaviPoint.location(withLatitude: 39.908791, longitude: 116.321257)!
    
    var routeIndicatorInfoArray = [RouteCollectionViewInfo]()
    var routeIndicatorView: UICollectionView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        
        initMapView()
        initRideManager()
        configSubview()
        initRouteIndicatorView()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        navigationController?.isNavigationBarHidden = false
        navigationController?.isToolbarHidden = true
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        addAnnotations()
    }
    
    // MARK: - Initalization
    
    func initMapView() {
        mapView = MAMapView(frame: CGRect(x: 0, y: routePlanInfoViewHeight, width: view.bounds.width, height: view.bounds.height - routePlanInfoViewHeight))
        mapView.delegate = self
        view.addSubview(mapView)
    }
    
    func initRideManager() {
        rideManager = AMapNaviRideManager()
        rideManager.delegate = self
    }
    
    func initRouteIndicatorView() {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        routeIndicatorView = UICollectionView(frame: CGRect(x: 0, y: view.bounds.height - routeIndicatorViewHeight, width: view.bounds.width, height: routeIndicatorViewHeight), collectionViewLayout: layout)
        
        guard let routeIndicatorView = routeIndicatorView else {
            return
        }
        
        routeIndicatorView.autoresizingMask = [.flexibleWidth, .flexibleTopMargin]
        routeIndicatorView.backgroundColor = UIColor.clear
        routeIndicatorView.isPagingEnabled = true
        routeIndicatorView.showsVerticalScrollIndicator = false
        routeIndicatorView.showsHorizontalScrollIndicator = false
        routeIndicatorView.delegate = self
        routeIndicatorView.dataSource = self
        
        routeIndicatorView.register(RouteCollectionViewCell.self, forCellWithReuseIdentifier: collectionCellIdentifier)
        view.addSubview(routeIndicatorView)
    }
    
    func addAnnotations() {
        let beginAnnotation = NaviPointAnnotation()
        beginAnnotation.coordinate = CLLocationCoordinate2D(latitude: Double(startPoint.latitude), longitude: Double(startPoint.longitude))
        beginAnnotation.title = "起始点"
        beginAnnotation.naviPointType = .start
        
        mapView.addAnnotation(beginAnnotation)
        
        let endAnnotation = NaviPointAnnotation()
        endAnnotation.coordinate = CLLocationCoordinate2D(latitude: Double(endPoint.latitude), longitude: Double(endPoint.longitude))
        endAnnotation.title = "终点"
        endAnnotation.naviPointType = .end
        
        mapView.addAnnotation(endAnnotation)
    }
    
    //MARK: - Button Action
    
    func routePlanAction(sender: UIButton) {
        //进行步行路径规划
        rideManager.calculateRideRoute(withStart: startPoint, end: endPoint)
    }
    
    //MARK: - Handle Navi Routes
    
    func showNaviRoutes() {
        
        guard let aRoute = rideManager.naviRoute else {
            return
        }
        
        mapView.removeOverlays(mapView.overlays)
        routeIndicatorInfoArray.removeAll()
        
        //将路径显示到地图上
        var coords = [CLLocationCoordinate2D]()
        for coordinate in aRoute.routeCoordinates {
            coords.append(CLLocationCoordinate2D.init(latitude: Double(coordinate.latitude), longitude: Double(coordinate.longitude)))
        }
        
        //-------------------------------2.线路规划完成后 将线路的所有关键坐标保存到数组--------------------------------
        self.coords = coords
        //添加路径Polyline
        let polyline = MAPolyline(coordinates: &coords, count: UInt(aRoute.routeCoordinates.count))!
        let selectablePolyline = SelectableOverlay(aOverlay: polyline)
        
        mapView.add(selectablePolyline)
        
        //更新CollectonView的信息
        let subtitle = String(format: "长度:%d米 | 预估时间:%d秒 | 分段数:%d", aRoute.routeLength, aRoute.routeTime, aRoute.routeSegments.count)
        let info = RouteCollectionViewInfo(routeID: 0, title: "路径信息:", subTitle: subtitle)
        
        routeIndicatorInfoArray.append(info)
        
        mapView.showAnnotations(mapView.annotations, animated: false)
        routeIndicatorView.reloadData()
        
        //-------------------------------4.绘制完规划线路时 调用补全线路方法 --------------------------------
        compleRoute()
        //记得在地图绘制折线的代理方法中添加补全线路样式的代码
    }
    
    
    //---------------------3.使用绘制地图折现方法 将线路开始/结束处的坐标 和开始/结束坐标点连起来--------------------------------
//MARK:补全规划路线
    func compleRoute() {
        if coords != nil  {
            var lineCoordinates: [CLLocationCoordinate2D] = [CLLocationCoordinate2D.init(latitude: (coords.first?.latitude)!, longitude: (coords.first?.longitude)!),CLLocationCoordinate2D.init(latitude: CLLocationDegrees(startPoint.latitude), longitude: CLLocationDegrees(startPoint.longitude))]
            let polyline: MAPolyline = MAPolyline(coordinates: &lineCoordinates, count: UInt(lineCoordinates.count))
            mapView.add(polyline)
            var lineCoordinates1: [CLLocationCoordinate2D] = [CLLocationCoordinate2D.init(latitude: (coords.last?.latitude)!, longitude: (coords.last?.longitude)!),CLLocationCoordinate2D.init(latitude: CLLocationDegrees(endPoint.latitude), longitude: CLLocationDegrees(endPoint.longitude))]
            let polyline1: MAPolyline = MAPolyline(coordinates: &lineCoordinates1, count: UInt(lineCoordinates1.count))
            mapView.add(polyline1)
        }
    }
    
    
    func selecteOverlayWithRouteID(routeID: Int) {
        guard let allOverlays = mapView.overlays else {
            return
        }
        
        for (index, aOverlay) in allOverlays.enumerated() {
            
            if let selectableOverlay = aOverlay as? SelectableOverlay {
                
                guard let overlayRenderer = mapView.renderer(for: selectableOverlay) as? MAPolylineRenderer else {
                    return
                }
                
                if selectableOverlay.routeID == routeID {
                    selectableOverlay.selected = true
                    
                    overlayRenderer.fillColor = selectableOverlay.selectedColor
                    overlayRenderer.strokeColor = selectableOverlay.selectedColor
                    
                    mapView.exchangeOverlay(at: UInt(index), withOverlayAt: UInt(allOverlays.count - 1))
                }
                else {
                    selectableOverlay.selected = false
                    
                    overlayRenderer.fillColor = selectableOverlay.reguarColor
                    overlayRenderer.strokeColor = selectableOverlay.reguarColor
                }
                
                overlayRenderer.glRender()
            }
        }
    }
    
    //MARK: - SubViews
    
    func configSubview() {
        let startPointLabel = UILabel(frame: CGRect(x: 0, y: 5, width: view.bounds.width, height: 20))
        startPointLabel.textAlignment = .center
        startPointLabel.font = UIFont.systemFont(ofSize: 14)
        startPointLabel.text = String(format: "起 点: %.6f, %.6f", startPoint.latitude, startPoint.longitude)
        
        view.addSubview(startPointLabel)
        
        let endPointLabel = UILabel(frame: CGRect(x: 0, y: 30, width: view.bounds.width, height: 20))
        endPointLabel.textAlignment = .center
        endPointLabel.font = UIFont.systemFont(ofSize: 14)
        endPointLabel.text = String(format: "终 点: %.6f, %.6f", endPoint.latitude, endPoint.longitude)
        
        view.addSubview(endPointLabel)
        
        let singleRouteBtn = buttonForTitle("路径规划")
        singleRouteBtn.frame = CGRect(x: (view.bounds.width - 80) / 2.0, y: 60, width: 80, height: 30)
        singleRouteBtn.addTarget(self, action: #selector(self.routePlanAction(sender:)), for: .touchUpInside)
        
        view.addSubview(singleRouteBtn)
    }
    
    private func buttonForTitle(_ title: String) -> UIButton {
        let reBtn = UIButton(type: .custom)
        
        reBtn.layer.borderColor = UIColor.lightGray.cgColor
        reBtn.layer.borderWidth = 0.5
        reBtn.layer.cornerRadius = 5
        
        reBtn.bounds = CGRect(x: 0, y: 0, width: 80, height: 30)
        reBtn.setTitle(title, for: .normal)
        reBtn.setTitleColor(UIColor.black, for: .normal)
        reBtn.titleLabel?.font = UIFont.systemFont(ofSize: 13)
        
        return reBtn
    }
    
    //MARK: - AMapNaviWalkManager Delegate
    
    func rideManager(_ rideManager: AMapNaviRideManager, error: Error) {
        let error = error as NSError
        NSLog("error:{%d - %@}", error.code, error.localizedDescription)
    }
    
    func rideManager(onCalculateRouteSuccess rideManager: AMapNaviRideManager) {
        NSLog("CalculateRouteSuccess")
        
        //算路成功后显示路径
        showNaviRoutes()
    }
    
    func rideManager(_ rideManager: AMapNaviRideManager, onCalculateRouteFailure error: Error) {
        let error = error as NSError
        NSLog("CalculateRouteFailure:{%d - %@}", error.code, error.localizedDescription)
    }
    
    func rideManager(_ rideManager: AMapNaviRideManager, didStartNavi naviMode: AMapNaviMode) {
        NSLog("didStartNavi");
    }
    
    func rideManagerNeedRecalculateRoute(forYaw rideManager: AMapNaviRideManager) {
        NSLog("needRecalculateRouteForYaw");
    }
    
    func rideManager(_ rideManager: AMapNaviRideManager, playNaviSound soundString: String, soundStringType: AMapNaviSoundType) {
        NSLog("playNaviSoundString:{%d:%@}", soundStringType.rawValue, soundString);
    }
    
    func rideManagerDidEndEmulatorNavi(_ rideManager: AMapNaviRideManager) {
        NSLog("didEndEmulatorNavi");
    }
    
    func rideManager(onArrivedDestination rideManager: AMapNaviRideManager) {
        NSLog("onArrivedDestination");
    }
    
    //MARK: - UICollectionViewDataSource
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return routeIndicatorInfoArray.count
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionCellIdentifier, for: indexPath) as! RouteCollectionViewCell
        cell.shouldShowPrevIndicator = (indexPath.row > 0 && indexPath.row < routeIndicatorInfoArray.count)
        cell.shouldShowNextIndicator = (indexPath.row >= 0 && indexPath.row < routeIndicatorInfoArray.count-1)
        cell.info = routeIndicatorInfoArray[indexPath.row]
        
        return cell
    }
    
    //MARK: - UICollectionViewDelegateFlowLayout
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: collectionView.bounds.width - 10, height: collectionView.bounds.height - 5)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsetsMake(0, 5, 5, 5)
    }
    
    //MARK: - MAMapView Delegate
    func mapView(_ mapView: MAMapView!, viewFor annotation: MAAnnotation!) -> MAAnnotationView! {
        
        if annotation is NaviPointAnnotation {
            let annotationIdentifier = "NaviPointAnnotationIdentifier"
            
            var pointAnnotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationIdentifier) as? MAPinAnnotationView
            
            if pointAnnotationView == nil {
                pointAnnotationView = MAPinAnnotationView(annotation: annotation, reuseIdentifier: annotationIdentifier)
            }
            
            pointAnnotationView?.animatesDrop = false
            pointAnnotationView?.canShowCallout = true
            pointAnnotationView?.isDraggable = false
            
            let annotation = annotation as! NaviPointAnnotation
            if annotation.naviPointType == .start {
                pointAnnotationView?.pinColor = .green
            }
            else if annotation.naviPointType == .end {
                pointAnnotationView?.pinColor = .red
            }
            
            return pointAnnotationView
        }
        return nil
    }
    
    func mapView(_ mapView: MAMapView!, rendererFor overlay: MAOverlay!) -> MAOverlayRenderer! {
        
        if overlay is SelectableOverlay {
            let selectableOverlay = overlay as! SelectableOverlay
            
            let polylineRenderer = MAPolylineRenderer(overlay: selectableOverlay.overlay)
            polylineRenderer?.lineWidth = 8.0
            polylineRenderer?.strokeColor = selectableOverlay.selected ? selectableOverlay.selectedColor : selectableOverlay.reguarColor
            
            return polylineRenderer
        }else if overlay.isKind(of: MAPolyline.self) {
//------------------------------5.自定义补全线路部分折现样式------------------------------------------------------
            let renderer: MAPolylineRenderer = MAPolylineRenderer(overlay: overlay)
            renderer.lineWidth = 8.0
            renderer.strokeColor = UIColor.cyan
            renderer.loadStrokeTextureImage(UIImage.init(named: "arrowTexture"))
            return renderer
        }
        return nil
    }
}

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

推荐阅读更多精彩内容