QSLRoadController.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. //
  2. // QSLRoadController.swift
  3. // QuickSearchLocation
  4. //
  5. // Created by Destiny on 2024/11/29.
  6. //
  7. import UIKit
  8. import MAMapKit
  9. import AMapFoundationKit
  10. import AMapLocationKit
  11. import BRPickerView
  12. enum QSLRoadJumpType: Int {
  13. case home
  14. case friend
  15. }
  16. class QSLRoadController: QSLBaseController {
  17. var type: QSLRoadJumpType?
  18. var userModel: QSLUserModel?
  19. // 高德地图
  20. lazy var roadMapView = {
  21. let _mapView = MAMapView()
  22. _mapView.delegate = self
  23. _mapView.minZoomLevel = 7;
  24. _mapView.maxZoomLevel = 19;
  25. _mapView.zoomLevel = 17;
  26. _mapView.showsCompass = false
  27. _mapView.showsScale = false
  28. _mapView.isRotateCameraEnabled = false
  29. return _mapView
  30. }()
  31. /// 高德地图定位
  32. lazy var roadMapLocationM = {
  33. let _homeMapLocationM = AMapLocationManager()
  34. _homeMapLocationM.delegate = self
  35. _homeMapLocationM.distanceFilter = 100
  36. _homeMapLocationM.locatingWithReGeocode = true
  37. _homeMapLocationM.desiredAccuracy = kCLLocationAccuracyHundredMeters
  38. _homeMapLocationM.locationTimeout = 2
  39. _homeMapLocationM.reGeocodeTimeout = 2
  40. _homeMapLocationM.pausesLocationUpdatesAutomatically = false
  41. _homeMapLocationM.allowsBackgroundLocationUpdates = true
  42. return _homeMapLocationM
  43. }()
  44. lazy var roadManager: MATraceManager = {
  45. let manager = MATraceManager()
  46. return manager
  47. }()
  48. lazy var roadLine: MAPolyline = {
  49. let line = MAPolyline()
  50. return line
  51. }()
  52. var beginAnnotation: MAPointAnnotation?
  53. var endAnnotation: MAPointAnnotation?
  54. var roadList: [QSLMapTrackModel]?
  55. lazy var backButton: UIButton = {
  56. let btn = UIButton()
  57. btn.setBackgroundImage(UIImage(named: "route_back_btn"), for: .normal)
  58. btn.addTarget(self, action: #selector(backBtnAction), for: .touchUpInside)
  59. return btn
  60. }()
  61. lazy var foldBtn: UIButton = {
  62. let btn = UIButton()
  63. // btn.isSelected = false
  64. btn.touchExtendInset = UIEdgeInsets(top: -20, left: -20, bottom: -20, right: -20)
  65. btn.addRadius(radius: 2.rpx)
  66. btn.backgroundColor = .hexStringColor(hexString: "#000000", alpha: 0.7)
  67. btn.addTarget(self, action: #selector(foldBtnAction), for: .touchUpInside)
  68. return btn
  69. }()
  70. lazy var mainView: QSLRoadMainView = {
  71. let view = QSLRoadMainView()
  72. view.delegate = self
  73. return view
  74. }()
  75. lazy var startDatePicker: BRDatePickerView = {
  76. let datePicker = BRDatePickerView()
  77. datePicker.pickerMode = .YMDHM
  78. datePicker.maxDate = self.nowDate
  79. let style = BRPickerStyle()
  80. style.topCornerRadius = 10.rpx
  81. style.doneTextColor = QSLColor.themeMainColor
  82. style.selectRowColor = .hexStringColor(hexString: "#EDFFF9")
  83. style.selectRowTextColor = QSLColor.themeMainColor
  84. style.clearPickerNewStyle = false
  85. datePicker.pickerStyle = style
  86. return datePicker
  87. }()
  88. lazy var endDatePicker: BRDatePickerView = {
  89. let datePicker = BRDatePickerView()
  90. datePicker.pickerMode = .YMDHM
  91. datePicker.maxDate = self.nowDate
  92. let style = BRPickerStyle()
  93. style.topCornerRadius = 10.rpx
  94. style.doneTextColor = QSLColor.themeMainColor
  95. style.selectRowColor = .hexStringColor(hexString: "#EDFFF9")
  96. style.selectRowTextColor = QSLColor.themeMainColor
  97. style.clearPickerNewStyle = false
  98. datePicker.pickerStyle = style
  99. return datePicker
  100. }()
  101. // 开始日期
  102. var startDate: Date = Date(timeIntervalSinceNow: -60 * 60 * 24)
  103. // 结束日期
  104. var endDate: Date = Date()
  105. // 现在日期
  106. var nowDate: Date = Date()
  107. init(userModel: QSLUserModel?) {
  108. super.init(nibName: nil, bundle: nil)
  109. self.userModel = userModel
  110. }
  111. @MainActor required init?(coder: NSCoder) {
  112. fatalError("init(coder:) has not been implemented")
  113. }
  114. override func viewDidLoad() {
  115. super.viewDidLoad()
  116. initView()
  117. if self.userModel?.remark.count != 0 {
  118. self.mainView.titleLabel.text = "\(self.userModel?.remark ?? "")的轨迹"
  119. } else {
  120. self.mainView.titleLabel.text = "\(self.userModel?.phone ?? "")的轨迹"
  121. }
  122. self.mainView.startTimeLabel.text = startDate.toformatterTimeString(formatter: "开始时间:yyyy-MM-dd HH:mm")
  123. self.mainView.endTimeLabel.text = endDate.toformatterTimeString(formatter: "结束时间:yyyy-MM-dd HH:mm")
  124. requestRoad()
  125. if let type = self.type {
  126. if type == .home {
  127. gravityInstance?.track(QSLGravityConst.road_show, properties: ["id": 1001])
  128. } else {
  129. gravityInstance?.track(QSLGravityConst.road_show, properties: ["id": 1002])
  130. }
  131. }
  132. }
  133. }
  134. extension QSLRoadController {
  135. @objc func foldBtnAction() {
  136. if !foldBtn.isSelected {
  137. UIView.animate(withDuration: 0.2) {
  138. self.mainView.qsl_y = QSLConst.qsl_kScreenH - 61.rpx
  139. self.foldBtn.qsl_y = QSLConst.qsl_kScreenH - 61.rpx - 6.rpx - 4.rpx
  140. }
  141. } else {
  142. UIView.animate(withDuration: 0.2) {
  143. self.mainView.qsl_y = QSLConst.qsl_kScreenH - 369.rpx
  144. self.foldBtn.qsl_y = QSLConst.qsl_kScreenH - 369.rpx - 6.rpx - 4.rpx
  145. }
  146. }
  147. foldBtn.isSelected = !foldBtn.isSelected
  148. }
  149. }
  150. extension QSLRoadController {
  151. // 查询轨迹
  152. func requestRoad() {
  153. self.roadMapView.remove(self.roadLine)
  154. self.roadMapView.removeAnnotations(self.roadMapView.annotations)
  155. let start = self.startDate.timeIntervalSince1970 * 1000
  156. let end = self.endDate.timeIntervalSince1970 * 1000
  157. var dict: [String: Any] = [String: Any]()
  158. dict["userId"] = self.userModel?.friendId
  159. dict["start"] = start
  160. dict["end"] = end
  161. QSLLoading.show()
  162. QSLNetwork().request(.locationTrackQuery(dict:dict)) { resposne in
  163. QSLLoading.hide()
  164. let list = resposne.mapArray(QSLMapTrackModel.self, modelKey: "data>list")
  165. self.roadList = list
  166. if list.count == 0 {
  167. QSLAlertView.alert(view: self.view, title: "温馨提示", content: "该时段内未查询到历史轨迹记录:\n\n1.可能是该用户未登录本软件;\n2.可能是该用户未运行我们的软件;\n 3.可能是对方未开启定位和网络连接等原因。", isOneBtn: true, oneBtnText: "我知道了")
  168. } else {
  169. self.drawLine()
  170. }
  171. } fail: { code, error in
  172. QSLLoading.hide()
  173. self.view.toast(text: error)
  174. }
  175. }
  176. }
  177. // MARK: - 设置地图相关方法
  178. extension QSLRoadController:MAMapViewDelegate, AMapLocationManagerDelegate {
  179. // 初始化高德地图设置
  180. func setUpMap() {
  181. AMapServices.shared().enableHTTPS = true
  182. AMapLocationManager.updatePrivacyShow(.didShow, privacyInfo: .didContain)
  183. AMapLocationManager.updatePrivacyAgree(.didAgree)
  184. roadMapLocationM.startUpdatingLocation()
  185. }
  186. // 申请地图定位权限
  187. func mapViewRequireLocationAuth(_ locationManager: CLLocationManager!) {
  188. locationManager.requestWhenInUseAuthorization()
  189. }
  190. func mapView(_ mapView: MAMapView!, viewFor annotation: (any MAAnnotation)!) -> MAAnnotationView! {
  191. if annotation is MAPointAnnotation {
  192. let reuseIdentifier = "pointReuseIdentifier"
  193. // 尝试从缓存池中重用AnnotationView
  194. var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier) as? QSLHomeAnnotatinView
  195. if annotationView == nil {
  196. annotationView = QSLHomeAnnotatinView(annotation: annotation, reuseIdentifier: reuseIdentifier)
  197. annotationView?.title = annotation.title
  198. }
  199. // 设置AnnotationView属性
  200. annotationView?.isEnabled = false
  201. annotationView?.image = UIImage(named: annotation.subtitle ?? "")
  202. annotationView?.canShowCallout = false
  203. // 设置偏移量
  204. annotationView?.centerOffset = CGPoint(x: 0, y: -18)
  205. annotationView?.calloutOffset = CGPoint(x: 0, y: -5)
  206. // 判断标题是否是“终点”,决定是否选中
  207. annotationView?.isSelected = true
  208. return annotationView
  209. }
  210. return nil
  211. }
  212. func mapView(_ mapView: MAMapView!, didSingleTappedAt coordinate: CLLocationCoordinate2D) {
  213. /*// 直接获取被点击的轨迹线(支持多段线同时选中)
  214. let hittedPolylines = mapView.getHittedPolylines(with: coordinate, traverseAll: false)
  215. if let polyline = hittedPolylines?.first as? MAPolyline {
  216. print("点击了轨迹线,包含 \(polyline.pointCount) 个点")
  217. ///点击轨迹
  218. if QSLBaseManager.shared.isVip() {
  219. gravityInstance?.track(QSLGravityConst.vip_location_click_Track, properties: ["id": 03006])
  220. } else {
  221. gravityInstance?.track(QSLGravityConst.location_click_Track, properties: ["id": 03007])
  222. }
  223. }*/
  224. }
  225. // // 查询个人位置
  226. // func searchMineLocation() {
  227. //
  228. // self.roadMapView.remove(self.roadLine)
  229. // self.roadMapView.removeAnnotations(self.roadMapView.annotations)
  230. //
  231. // self.roadMapLocationM.requestLocation(withReGeocode: true) { location, regeocode, error in
  232. //
  233. // if let error = error as? NSError {
  234. //
  235. // if error.code == AMapLocationErrorCode.locateFailed.rawValue {
  236. // return
  237. // }
  238. // }
  239. //
  240. // let beginPoint = MAPointAnnotation()
  241. // if let location = location {
  242. // let beginLocation = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.latitude)
  243. // beginPoint.coordinate = beginLocation
  244. // beginPoint.title = self.userModel?.remark
  245. // beginPoint.subtitle = ""
  246. // self.beginAnnotation = beginPoint
  247. //
  248. // self.roadMapView.addAnnotation(self.beginAnnotation)
  249. // self.roadMapView.setCenter(location.coordinate, animated: true)
  250. //
  251. // print("当前位置:\(location)")
  252. // }
  253. //
  254. // if let regeocode = regeocode {
  255. // print("当前地址:\(regeocode)")
  256. // self.mainView.startAddressLabel.text = "起点:\(regeocode)"
  257. // }
  258. // }
  259. // }
  260. //
  261. // // 查询其他用户位置
  262. // func searchOthersLocation() {
  263. //
  264. // self.roadMapView.remove(self.roadLine)
  265. // self.roadMapView.removeAnnotations(self.roadMapView.annotations)
  266. //
  267. //
  268. // if let model = self.userModel {
  269. //
  270. // QSLLoading.show()
  271. // QSLNetwork().request(.friendGet(dict: ["friendId": model.userId])) { response in
  272. //
  273. // QSLLoading.hide()
  274. // let user = response.mapObject(QSLUserModel.self, modelKey: "data")
  275. // var beginPoint = MAPointAnnotation()
  276. // var beginLocation = CLLocationCoordinate2D(latitude: model.location.lat, longitude: model.location.lng)
  277. // beginPoint.coordinate = beginLocation
  278. // beginPoint.title = self.userModel?.remark
  279. // beginPoint.subtitle = ""
  280. // self.beginAnnotation = beginPoint
  281. //
  282. // self.roadMapView.addAnnotation(self.beginAnnotation)
  283. //
  284. // self.roadMapView.setCenter(beginLocation, animated: true)
  285. // self.mainView.startAddressLabel.text = "起点:\(model.location.addr)"
  286. // } fail: { code, error in
  287. //
  288. // QSLLoading.hide()
  289. // self.view.toast(text: error)
  290. // }
  291. // }
  292. // }
  293. //绘制路线
  294. func mapView(_ mapView: MAMapView!, rendererFor overlay: MAOverlay!) -> MAOverlayRenderer! {
  295. if overlay.isKind(of: MAPolyline.self) {
  296. let polylineRender = MAPolylineRenderer.init(overlay: overlay)
  297. polylineRender?.lineWidth = 4
  298. polylineRender?.strokeColor = QSLColor.themeMainColor
  299. polylineRender?.fillColor = QSLColor.themeMainColor
  300. polylineRender?.lineJoinType = kMALineJoinRound
  301. polylineRender?.lineCapType = kMALineCapRound
  302. return polylineRender
  303. }
  304. return nil
  305. }
  306. // 绘制轨迹
  307. func drawLine() {
  308. var MATraceList: [MATraceLocation] = []
  309. guard let roadList = self.roadList else { return }
  310. for model in roadList {
  311. let location = MATraceLocation()
  312. location.speed = model.speed
  313. location.time = model.ts
  314. location.angle = model.bearing
  315. var loc = CLLocationCoordinate2D()
  316. loc.latitude = model.lat
  317. loc.longitude = model.lng
  318. location.loc = loc
  319. MATraceList.append(location)
  320. }
  321. self.roadManager.queryProcessedTrace(with: MATraceList, type: .aMap) { index, points in
  322. } finishCallback: { points, distance in
  323. print("轨迹纠偏success")
  324. // 纠偏成功添加纠偏后的折线
  325. if let points = points {
  326. var commonPolylineCoords = [CLLocationCoordinate2D](repeating: CLLocationCoordinate2D(), count: points.count)
  327. for i in 0..<points.count {
  328. commonPolylineCoords[i].latitude = points[i].latitude
  329. commonPolylineCoords[i].longitude = points[i].longitude
  330. }
  331. // 构造折线对象
  332. if let commonPolyline = MAPolyline(coordinates: &commonPolylineCoords, count: UInt(points.count)) {
  333. self.roadLine = commonPolyline
  334. // 在地图上添加折线对象
  335. self.roadMapView.add(self.roadLine)
  336. //调用划线后,调用下面方法,设置地图可视矩形的范围
  337. self.roadMapView.setVisibleMapRect(self.roadLine.boundingMapRect, edgePadding: UIEdgeInsets(top: 40, left: 40, bottom: 40, right: 40), animated: true)
  338. }
  339. // 添加起点图标
  340. if let startTrack = points.first {
  341. let startPoint = MAPointAnnotation()
  342. startPoint.coordinate = CLLocationCoordinate2D(latitude: startTrack.latitude, longitude: startTrack.longitude)
  343. startPoint.title = "起点"
  344. startPoint.subtitle = "road_begin_icon"
  345. self.beginAnnotation = startPoint
  346. }
  347. // 添加终点图标
  348. if let endTrack = points.last {
  349. let endPoint = MAPointAnnotation()
  350. endPoint.coordinate = CLLocationCoordinate2D(latitude: endTrack.latitude, longitude: endTrack.longitude)
  351. endPoint.title = "终点"
  352. endPoint.subtitle = "road_end_icon"
  353. self.endAnnotation = endPoint
  354. }
  355. // 设置地址
  356. if let startModel = self.roadList?.first,
  357. let endModel = self.roadList?.last {
  358. self.mainView.startAddressLabel.text = "起点:\(startModel.addr)"
  359. self.mainView.endAddressLabel.text = "终点:\(endModel.addr)"
  360. }
  361. // 添加起点和终点图标
  362. if let startPoint = self.beginAnnotation,
  363. let endPoint = self.endAnnotation {
  364. self.roadMapView.addAnnotation(startPoint)
  365. self.roadMapView.addAnnotation(endPoint)
  366. }
  367. }
  368. } failedCallback: { code, error in
  369. print("轨迹纠偏FailError: \(error ?? "")")
  370. // 纠偏失败添加原来的折线
  371. if let roadList = self.roadList {
  372. var commonPolylineCoords = [CLLocationCoordinate2D](repeating: CLLocationCoordinate2D(), count: roadList.count)
  373. for i in 0..<roadList.count {
  374. commonPolylineCoords[i].latitude = roadList[i].lat
  375. commonPolylineCoords[i].longitude = roadList[i].lng
  376. }
  377. // 构造折线对象
  378. if let commonPolyline = MAPolyline(coordinates: &commonPolylineCoords, count: UInt(roadList.count)) {
  379. self.roadLine = commonPolyline
  380. // 在地图上添加折线对象
  381. self.roadMapView.add(self.roadLine)
  382. //调用划线后,调用下面方法,设置地图可视矩形的范围
  383. self.roadMapView.setVisibleMapRect(self.roadLine.boundingMapRect, edgePadding: UIEdgeInsets(top: 40, left: 40, bottom: 40, right: 40), animated: true)
  384. }
  385. // 添加起点图标
  386. if let startTrack = roadList.first {
  387. let startPoint = MAPointAnnotation()
  388. startPoint.coordinate = CLLocationCoordinate2D(latitude: startTrack.lat, longitude: startTrack.lng)
  389. startPoint.title = "起点"
  390. startPoint.subtitle = "road_begin_icon"
  391. self.beginAnnotation = startPoint
  392. }
  393. // 添加终点图标
  394. if let endTrack = roadList.last {
  395. let endPoint = MAPointAnnotation()
  396. endPoint.coordinate = CLLocationCoordinate2D(latitude: endTrack.lat, longitude: endTrack.lng)
  397. endPoint.title = "终点"
  398. endPoint.subtitle = "road_end_icon"
  399. self.endAnnotation = endPoint
  400. }
  401. // 设置地址
  402. if let startTrack = roadList.first, let endTrack = roadList.last {
  403. self.mainView.startAddressLabel.text = "起点:\(startTrack.addr)"
  404. self.mainView.endAddressLabel.text = "终点:\(endTrack.addr)"
  405. }
  406. // 添加起点和终点注释
  407. if let startPoint = self.beginAnnotation,
  408. let endPoint = self.endAnnotation {
  409. self.roadMapView.addAnnotation(startPoint)
  410. self.roadMapView.addAnnotation(endPoint)
  411. }
  412. }
  413. }
  414. }
  415. }
  416. extension QSLRoadController: QSLRoadMainViewDelegate {
  417. func searchClickAction() {
  418. gravityInstance?.track(QSLGravityConst.road_search)
  419. self.requestRoad()
  420. }
  421. // 开始时间点击
  422. func startTimeClickAction() {
  423. self.startDatePicker.selectDate = self.startDate
  424. self.startDatePicker.show()
  425. self.startDatePicker.resultBlock = { [weak self] date, value in
  426. gravityInstance?.track(QSLGravityConst.road_time_confirm)
  427. self?.mainView.startTimeLabel.text = "开始时间:\(value ?? "")"
  428. if let date = date {
  429. self?.startDate = date
  430. // 获取目标时间(加24小时)
  431. var nextDay = date.addingTimeInterval(24 * 60 * 60)
  432. // 获取时间戳
  433. let startTime = date.timeIntervalSince1970
  434. let nowTime = self?.nowDate.timeIntervalSince1970
  435. // 判断时间差是否小于24小时
  436. if (nowTime ?? 0) - startTime < 24 * 60 * 60 {
  437. nextDay = self?.nowDate ?? Date() // 当前时间
  438. }
  439. self?.mainView.endTimeLabel.text = nextDay.toformatterTimeString(formatter: "结束时间:yyyy-MM-dd HH:mm")
  440. self?.endDate = nextDay
  441. self?.endDatePicker.selectDate = self?.endDate
  442. }
  443. }
  444. self.startDatePicker.cancelBlock = {
  445. gravityInstance?.track(QSLGravityConst.road_time_cancel)
  446. }
  447. }
  448. // 结束时间点击
  449. func endTimeClickAction() {
  450. self.endDatePicker.selectDate = self.endDate
  451. self.endDatePicker.show()
  452. self.endDatePicker.resultBlock = { [weak self] date, value in
  453. gravityInstance?.track(QSLGravityConst.road_time_confirm)
  454. self?.mainView.endTimeLabel.text = "结束时间:\(value ?? "")"
  455. if let date = date {
  456. self?.endDate = date
  457. }
  458. }
  459. self.endDatePicker.cancelBlock = {
  460. gravityInstance?.track(QSLGravityConst.road_time_cancel)
  461. }
  462. }
  463. }
  464. extension QSLRoadController {
  465. func initView() {
  466. self.view.addSubview(roadMapView)
  467. roadMapView.snp.makeConstraints { make in
  468. make.top.right.left.equalTo(0)
  469. make.edges.equalToSuperview()
  470. }
  471. self.view.addSubview(mainView)
  472. mainView.snp.makeConstraints { make in
  473. make.left.right.bottom.equalTo(0)
  474. make.height.equalTo(369.rpx)
  475. }
  476. self.view.addSubview(foldBtn)
  477. foldBtn.snp.makeConstraints { make in
  478. make.size.equalTo(CGSize(width: 20.rpx, height: 4.rpx))
  479. make.centerX.equalToSuperview()
  480. make.bottom.equalTo(mainView.snp.top).offset(-6.rpx)
  481. }
  482. self.view.addSubview(backButton)
  483. backButton.snp.makeConstraints { make in
  484. make.size.equalTo(CGSize(width: 50.rpx, height: 50.rpx))
  485. make.left.equalTo(0)
  486. make.top.equalTo(QSLConst.qsl_kStatusBarFrameH)
  487. }
  488. }
  489. }