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

news/2024/7/20 22:01:25 标签: ios, swift, cocoa, 高德地图

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

swift">pod 'AMapSearch'

定义AMapSearchAPI

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

swift">import AMapSearchKit

var searchApi:AMapSearchAPI!

在这里插入图片描述

构造 AMapSearchAPI

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

在这里插入图片描述

设置驾车线路规划参数

swift">//请求参数类
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)!

发起驾车路线规划

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

在回调中处理数据

实现代理方法onRouteSearchDone

swift">    //路径搜索结果
    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)
        }
    }
swift">    //转数组
    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,否则无效;若设置了纹理图片,设置线颜色、连接类型和端点类型将无效。

swift">    //路径绘制代理
    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
    }

另外,要是有箭头的话,记得要是箭头向下的,向上的话实际显示箭头会反过来,奇奇怪怪的
在这里插入图片描述

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

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

swift">//图标设置代理
    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
    }

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

结果

在这里插入图片描述


http://www.niftyadmin.cn/n/5330211.html

相关文章

[leetcode~数位动态规划] 2719. 统计整数数目 hard

给你两个数字字符串 num1 和 num2 &#xff0c;以及两个整数 max_sum 和 min_sum 。如果一个整数 x 满足以下条件&#xff0c;我们称它是一个好整数&#xff1a; num1 < x < num2 min_sum < digit_sum(x) < max_sum. 请你返回好整数的数目。答案可能很大&#xff…

Kafka-生产者

Kafka在实际应用中&#xff0c;经常被用作高性能、可扩展的消息中间件。 Kafka自定义了一套网络协议&#xff0c;只要遵守这套协议的格式&#xff0c;就可以向Kafka发送消息&#xff0c;也可以从Kafka中拉取消息。 在实践生产过程中&#xff0c;一套API封装良好、灵活易用的客…

Angular系列教程之观察者模式和RxJS

文章目录 引言RxJS简介RxJS中的设计模式观察者模式迭代器模式 示例代码RxJS 在 Angular 中的应用总结 引言 在Angular开发中&#xff0c;我们经常需要处理异步操作&#xff0c;例如从后端获取数据或与用户的交互。为了更好地管理这些异步操作&#xff0c;Angular中引入了RxJS&…

解决C语言wprintf函数无法打印中文的问题

在Visual Studio中&#xff0c;wchar_t[]字符数组用来存储UTF-16编码的字符串&#xff0c;但C语言库函数wprintf无法打印含有汉字的wchar_t字符串。 解决办法是用WriteConsoleW函数重新实现一个自己的my_wprintf函数。 #include <stdio.h> #include <Windows.h>//…

Redis主从+哨兵集群(基于CentOS-8.0)高可用部署方案

目录 一、环境描述 二、Redis 主从集群部署 2.1 Redis下载 2.2 Redis解压 和移动文件 2.4 编译、安装Redis 2.6 新建 bin 和 etc 文件夹 2.7 分发Redis 2.8 配置 2.8.1 主节点配置 2.8.2 从节点配置 2.9 启动Redis服务 2.10 验证主从服务 2.11 查看节点角色信息 2…

camke搜索文件命令

camke搜索文件命令 搜索目录下的文件 aux_source_directory(<dir> varibale) # dir:路径 # variable:将从dir目录下搜索要找到的源文件列表存储到改方式二&#xff1a; file 命令&#xff1a; file(GLOB/GLOB_RECURCE 变量名 要搜索的文件路径和文件类型) # GLOB:将指…

找不到mfc100.dll的解决方法,怎么修复mfc100.dll文件

当我们在使用电脑时&#xff0c;时常可能会遇到各类系统提示的错误信息。"找不到mfc100.dll" 就是这些错误之一&#xff0c;该错误提示会妨碍我们执行一些应用程序或特定代码。为了帮助读者克服这个技术障碍&#xff0c;本篇文章将详尽阐明导致该问题的根本原因&…

【目标检测实验系列】YOLOv5模型改进:融入坐标注意力机制CA,多维度关注数据特征,高效涨点!(内含源代码,超详细改进代码流程)

自我介绍&#xff1a;本人硕士期间全程放养&#xff0c;目前成果:一篇北大核心CSCD录用,两篇中科院三区已见刊&#xff0c;一篇中科院四区在投。如何找创新点&#xff0c;如何放养过程厚积薄发&#xff0c;如何写中英论文&#xff0c;找期刊等等。本人后续会以自己实战经验详细…