IOS-高德地图路径绘制-Swift

本文展示的是在IOS开发中调用高德地图进行驾车路径绘制,开发语言是Swift。
IOS高德地图集成请看:IOS集成高德地图Api
使用路径规划功能需要集成高德地图的搜索功能。

pod 'AMapSearch'

定义AMapSearchAPI

定义主搜索对象 AMapSearchAPI ,并继承搜索协议。

import AMapSearchKit

var searchApi:AMapSearchAPI!

在这里插入图片描述

构造 AMapSearchAPI

searchApi=AMapSearchAPI()
searchApi.delegate=self
//起点终点
startCoordinate        = CLLocationCoordinate2DMake(39.910267, 116.370888)
destinationCoordinate  = CLLocationCoordinate2DMake(39.989872, 116.481956)

IOS-高德地图路径绘制-Swift_第1张图片

设置驾车线路规划参数

//请求参数类
let request=AMapDrivingCalRouteSearchRequest()
//设置起点
request.origin = AMapGeoPoint.location(withLatitude: CGFloat(startCoordinate.latitude), longitude: CGFloat(startCoordinate.longitude))
//设置终点
request.destination = AMapGeoPoint.location(withLatitude: CGFloat(destinationCoordinate.latitude), longitude: CGFloat(destinationCoordinate.longitude))
//显示字段类型
request.showFieldType = AMapDrivingRouteShowFieldType.init(rawValue: AMapDrivingRouteShowFieldType.cost.rawValue|AMapDrivingRouteShowFieldType.tmcs.rawValue|AMapDrivingRouteShowFieldType.navi.rawValue|AMapDrivingRouteShowFieldType.cities.rawValue|AMapDrivingRouteShowFieldType.polyline.rawValue)!

发起驾车路线规划

//发起驾车路线规划
searchApi.aMapDrivingV2RouteSearch(request)

在回调中处理数据

实现代理方法onRouteSearchDone

    //路径搜索结果
    func onRouteSearchDone(_ request: AMapRouteSearchBaseRequest!, response: AMapRouteSearchResponse!) {

        // 取出第一种路线方案
        let stringWithOptional = response.route.paths.first?.polyline!
        let distance=response.route.paths.first?.distance
        let time=response.route.paths.first?.duration
        
        print("距离:\(distance!)米,预计耗时:\(time!)秒")
        let result = convertToArray(stringWithOptional)
        if var temp = result {
            let polyline = MAPolyline.init(coordinates: &temp, count: UInt(temp.count))
            mapView.add(polyline)
        }
    }
    //转数组
    func convertToArray(_ coordinatesString: String!) -> [CLLocationCoordinate2D]? {
        // 去掉 "Optional(" 和 ")" 前缀和后缀
        let cleanedString = coordinatesString.replacingOccurrences(of: "Optional(\"", with: "").replacingOccurrences(of: "\")", with: "")
        
        var corArray = [CLLocationCoordinate2D]()
        let coordinatesArray = cleanedString.components(separatedBy: ";")
        
        for coordinate in coordinatesArray {
            let components = coordinate.components(separatedBy: ",")
            if components.count == 2, let longitude = Double(components[0]), let latitude = Double(components[1]) {
                let cor = CLLocationCoordinate2D.init(latitude: CLLocationDegrees(CGFloat(latitude)), longitude: CLLocationDegrees(CGFloat(longitude)))
                                        
                    corArray.append(cor)
            } else {
                return nil
            }
        }
        return corArray
    }

路线绘制

arrowTexture是图片资源文件,按照官方文档的说法:纹理图片须是正方形,宽高是2的整数幂,如64*64,否则无效;若设置了纹理图片,设置线颜色、连接类型和端点类型将无效。

    //路径绘制代理
    func mapView(_ mapView: MAMapView!, rendererFor overlay: MAOverlay!) -> MAOverlayRenderer! {
        if let tempOver = overlay as? MAPolyline {
            let polygonView = MAPolylineRenderer.init(polyline: (overlay as! MAPolyline))
            // 参数设置
            polygonView?.lineWidth = 10.0
            polygonView?.strokeImage=UIImage.init(resource: ImageResource.arrowTexture)
            
          return polygonView
        }
        return nil
    }

另外,要是有箭头的话,记得要是箭头向下的,向上的话实际显示箭头会反过来,奇奇怪怪的
IOS-高德地图路径绘制-Swift_第2张图片

起点终点图标设置(可跳过)

需要实现这个代理,不设置也会有默认的大头针图标
default_common_route_startpoint_normal、default_common_route_endpoint_normal是图标资源文件

//图标设置代理
    func mapView(_ mapView: MAMapView!, viewFor annotation: MAAnnotation!) -> MAAnnotationView! {
        let pointReuseIndetifier = "pointReuseIndetifier"
        var annotationView: MAAnnotationView? = mapView.dequeueReusableAnnotationView(withIdentifier: pointReuseIndetifier)
        
        if annotationView == nil {
            annotationView = MAAnnotationView(annotation: annotation, reuseIdentifier: pointReuseIndetifier)
            annotationView!.canShowCallout = true
            annotationView!.isDraggable = false
        }
        annotationView!.image = nil
        if annotation.title == "起点" {
            annotationView!.image = UIImage(named: "default_common_route_startpoint_normal")
        }
        else if annotation.title == "终点" {
            annotationView!.image = UIImage(named: "default_common_route_endpoint_normal")
        }
        return annotationView
    }

在这里插入图片描述
在这里插入图片描述

结果

IOS-高德地图路径绘制-Swift_第3张图片

你可能感兴趣的:(IOS-Swift学习,ios,swift,cocoa,高德地图)