ISO Swift高德导航开发指南

发布于:2024-04-19 ⋅ 阅读:(31) ⋅ 点赞:(0)

开发环境

xode:12.0
模拟器:iphone 14 plus
cocoapods:1.15.2
swift:5.7.1
ios:16.1(20B72)

IOS包管理工具cocoapods

官网地址:https://cocoapods.org/

方式1:安装指令

sudo gem install cocoapods

方式2:直接下载安装包安装
安装包下载地址:https://cocoapods.org/app

进入应用目录,并初始化cocoapods

cd ~/Desktop/Workspaces/MapKitDemo
pod init;
vim Podfile

添加依赖
http请求工具:Alamofire
JOSN转换工具:SwiftyJSON
JSON转对象插件:HandyJSON
高德导航依赖:AMapNaviAMapSearch

  pod "AMapNavi" , "10.0.600"
  pod "AMapSearch" , "9.7.0"
  pod "SwiftyJSON" , "5.0.2"
  pod "HandyJSON" , "5.0.2"
  pod "Alamofire" , "~> 5.2"

执行安装依赖命令

pod install

后续增加依赖可修改Podfile文件,增加pod配置,再执行pod install命令

打开应用

安装cocoapods的应用,不能直接打开.xcodeproj文件,需要打开生成的.xcworkspace文件

open MapKitDemo.xcworkspace/

申请高德开放平台Key

https://lbs.amap.com/api/ios-navi-sdk/guide/create-project/get-key

AMapServices.shared().apiKey = ""

隐私合规说明
在调用任何一个导航manager之前必须进行合规检查,设置接口之前保证隐私政策合规,检查接口如下:

AMapNaviManagerConfig.shared().updatePrivacyShow(.didShow, privacyInfo: .didContain)
AMapNaviManagerConfig.shared().updatePrivacyAgree(.didAgree)

权限配置

修改info.plist配置文件,添加非https网络请求服务、定位服务、语音播报服务、后台定位服务

	<key>NSAppTransportSecurity</key>
	<dict>
		<key>NSAllowsArbitraryLoads</key>
		<true/>
	</dict>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>导航SDK需要您的定位服务,否则可能无法使用,如果您需要使用后台导航功能请选择“始终允许”。</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>导航SDK需要您的定位服务,否则可能无法使用。</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>导航SDK需要您的定位服务,否则可能无法使用。</string>
<key>UIBackgroundModes</key>
<array>
	<string>audio</string>
	<string>location</string>
</array>

开启定位服务

import UIKit
import CoreLocation

class ViewController: UIViewController,CLLocationManagerDelegate {
   
    let locationManage = CLLocationManager()
   
    override func viewDidLoad() {
        super.viewDidLoad()
        locationManage.delegate=self
        locationManage.desiredAccuracy = kCLLocationAccuracyBest//设置位置精度
        locationManage.requestLocation()//请求用户位置,仅一次
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        locationManage.requestWhenInUseAuthorization()//请求授权获取定位
        
    }
    
    //请求位置时自动调用
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let latitude=locations[0].coordinate.latitude
        let longitude=locations[0].coordinate.longitude
        print(latitude,longitude)
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("获取定位失败",error)
    }
   
}

初始化 AMapNaviCompositeManager

import UIKit
import AMapNaviKit
import AMapFoundationKit

class MapNavController:UIViewController,AMapNaviCompositeManagerDelegate{
    override func viewDidLoad() {
        super.viewDidLoad()

        initNavi()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        //在显示地图前需要进行隐私合规设置
        AMapNaviManagerConfig.shared().updatePrivacyShow(.didShow, privacyInfo: .didContain)
        AMapNaviManagerConfig.shared().updatePrivacyAgree(.didAgree)

    }

	//初始化导航
	func initNavi(){
	    
	    self.view.backgroundColor = UIColor.white;
	    
	    //创建进入导航的按钮
	    let routeBtn = UIButton(configuration: UIButton.Configuration.tinted(), primaryAction: nil)
	    routeBtn.frame = CGRect.init(x: (UIScreen.main.bounds.size.width - 200) / 2.0, y: 200.0, width: 200.0, height: 45.0)
	    routeBtn.setTitle("打开导航", for: UIControl.State.normal)
	    routeBtn.setTitleColor(UIColor.init(red: 53/255.0, green: 117/255.0, blue: 255/255.0, alpha: 1), for: UIControl.State.normal)
	    routeBtn.layer.cornerRadius = 5
	    routeBtn.layer.borderColor = UIColor.init(red: 53/255.0, green: 117/255.0, blue: 255/255.0, alpha: 1).cgColor
	    routeBtn.layer.borderWidth = 1
	    routeBtn.addTarget(self, action: #selector(self.openNavPage),for: UIControl.Event.touchUpInside)
	    self.view.addSubview(routeBtn)
	    
	    //初始化导航组件
	    self.compositeManager = AMapNaviCompositeManager.init()
	    self.compositeManager.delegate = self
	}

    //打开导航页面
    @objc func openNavPage() {
        let config = AMapNaviCompositeUserConfig.init()
        
        let info = AMapNaviVehicleInfo.init()
       //设置车辆类型, 0:燃油客车; 1:燃油货车; 2:纯电动客车; 3:纯电动货车; 4:插电式混动客车; 5:插电式混动货车; since 8.0.0 新增11:摩托车. 默认0(小车). 注意:只有设置了货车, 其他关于货车的属性设置才会生效
        info.type = 0;
        config.setVehicleInfo(info);
        info.vehicleId = "浙F-12345";
        let startLat:Double = 39.902896
        let startLon:Double = 116.42792
        let startCity:String ="北京站"
        config.setRoutePlanPOIType(AMapNaviRoutePlanPOIType.start, location: AMapNaviPoint.location(withLatitude: startLat, longitude: startLon), name: startCity, poiId: nil)
            //最多3个途径点
        let lat:Double= 39.975642
        let lon:Double= 116.306332
        let city:String = "苏州街(地铁站)"
        config.setRoutePlanPOIType(AMapNaviRoutePlanPOIType.way, location: AMapNaviPoint.location(withLatitude: lat, longitude: lon), name: city, poiId: nil)
            
       let endLat:Double = 39.894914
       let endLon:Double = 116.322062
       let endCity:String = "北京西站"
       config.setRoutePlanPOIType(AMapNaviRoutePlanPOIType.end, location: AMapNaviPoint.location(withLatitude: endLat, longitude: endLon), name: endCity, poiId: nil)
        //通过parsent方式显示路线规划页面
        self.compositeManager.presentRoutePlanViewController(withOptions: config)
    }

    // MARK: - AMapNaviCompositeManagerDelegate
    /**
     * @brief 发生错误时,会调用此方法
     * @param compositeManager 导航组件类
     * @param error 错误信息
     */
    func compositeManager(_ compositeManager: AMapNaviCompositeManager, error: Error) {
        let error = error as NSError
        NSLog("导航异常:{%d - %@}", error.code, error.localizedDescription)
    }
    /**
     * @brief 算路成功后的回调函数, 路径规划页面的算路、导航页面的重算等成功后均会调用此方法
     * @param compositeManager 导航组件类
     */
    func compositeManager(onCalculateRouteSuccess compositeManager: AMapNaviCompositeManager ){
        NSLog("导航算路成功,%ld", compositeManager.naviRouteID)
    }

    /**
     * @brief 开始导航的回调函数
     * @param compositeManager 导航组件类
     * @param naviMode 导航类型,参考 AMapNaviMode .
     */
    func compositeManager(_ compositeManager: AMapNaviCompositeManager, didStartNavi naviMode: AMapNaviMode) {
        NSLog("开始导航")
    }
    
    
    /**
     * @brief 导航到达目的地后的回调函数
     * @param compositeManager 导航组件类
     * @param naviMode 导航类型,参考 AMapNaviMode .
     */
    func compositeManager(_ compositeManager:AMapNaviCompositeManager , didArrivedDestination naviMode :AMapNaviMode){
        NSLog("导航到达目")
    }

    /**
     * @brief 导航组件页面回退或者退出导航组件时会调用此函数 since 5.5.0
     * @param compositeManager 导航组件类
     * @param backwardActionType 导航组件页面回退的动作类型,参考 AMapNaviCompositeVCBackwardActionType .
     */
    func compositeManager(_ compositeManager:AMapNaviCompositeManager ,didBackwardAction backwardActionType:AMapNaviCompositeVCBackwardActionType){
        NSLog("导航组件页面回退或者退出导航")
    }

    /**
     * @brief 每次进入导航组件时和驾车路径规划策略改变均会调用此方法 since 6.1.0
     * @param compositeManager 导航组件类
     * @param driveStrategy 驾车路径规划策略,参考 AMapNaviDrivingStrategy .
     */
    func compositeManager(_ compositeManager:AMapNaviCompositeManager ,onDriveStrategyChanged driveStrategy:AMapNaviDrivingStrategy){
        NSLog("进入导航")
    }

    /**
     * @brief 导航到达某个途经点的回调函数 since 6.1.0
     * @param compositeManager 导航组件类
     * @param wayPointIndex 到达途径点的编号,标号从0开始. 注意:如果导航过程进行了路径重算(包含偏航、手动刷新等),wayPointIndex会重新从0开始计数
     */
    func compositeManager(_ compositeManager:AMapNaviCompositeManager ,onArrivedWayPoint wayPointIndex:Int){
        NSLog("导航到达某个途经点")
    }
}

开启弹出导航页面窗口配置

修改AppDelegate文件,增加UIWindow配置

import AMapFoundationKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        let viewController = ViewController()
        window = UIWindow(frame: UIScreen.main.bounds);
        window!.rootViewController = UINavigationController(rootViewController: viewController)
        window!.backgroundColor = UIColor.white
        window!.makeKeyAndVisible()
        
        AMapServices.shared().apiKey = "" //高德KEY
        //高德 iOS SDK 支持苹果 ATS 安全功能的方案,为保证应用在提交 AppStore 时不受影响,需要开启 HTTPS 功能
        AMapServices.shared().enableHTTPS = true
        return true
    }
}