QSLRoadController.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  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. // // 查询个人位置
  213. // func searchMineLocation() {
  214. //
  215. // self.roadMapView.remove(self.roadLine)
  216. // self.roadMapView.removeAnnotations(self.roadMapView.annotations)
  217. //
  218. // self.roadMapLocationM.requestLocation(withReGeocode: true) { location, regeocode, error in
  219. //
  220. // if let error = error as? NSError {
  221. //
  222. // if error.code == AMapLocationErrorCode.locateFailed.rawValue {
  223. // return
  224. // }
  225. // }
  226. //
  227. // let beginPoint = MAPointAnnotation()
  228. // if let location = location {
  229. // let beginLocation = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.latitude)
  230. // beginPoint.coordinate = beginLocation
  231. // beginPoint.title = self.userModel?.remark
  232. // beginPoint.subtitle = ""
  233. // self.beginAnnotation = beginPoint
  234. //
  235. // self.roadMapView.addAnnotation(self.beginAnnotation)
  236. // self.roadMapView.setCenter(location.coordinate, animated: true)
  237. //
  238. // print("当前位置:\(location)")
  239. // }
  240. //
  241. // if let regeocode = regeocode {
  242. // print("当前地址:\(regeocode)")
  243. // self.mainView.startAddressLabel.text = "起点:\(regeocode)"
  244. // }
  245. // }
  246. // }
  247. //
  248. // // 查询其他用户位置
  249. // func searchOthersLocation() {
  250. //
  251. // self.roadMapView.remove(self.roadLine)
  252. // self.roadMapView.removeAnnotations(self.roadMapView.annotations)
  253. //
  254. //
  255. // if let model = self.userModel {
  256. //
  257. // QSLLoading.show()
  258. // QSLNetwork().request(.friendGet(dict: ["friendId": model.userId])) { response in
  259. //
  260. // QSLLoading.hide()
  261. // let user = response.mapObject(QSLUserModel.self, modelKey: "data")
  262. // var beginPoint = MAPointAnnotation()
  263. // var beginLocation = CLLocationCoordinate2D(latitude: model.location.lat, longitude: model.location.lng)
  264. // beginPoint.coordinate = beginLocation
  265. // beginPoint.title = self.userModel?.remark
  266. // beginPoint.subtitle = ""
  267. // self.beginAnnotation = beginPoint
  268. //
  269. // self.roadMapView.addAnnotation(self.beginAnnotation)
  270. //
  271. // self.roadMapView.setCenter(beginLocation, animated: true)
  272. // self.mainView.startAddressLabel.text = "起点:\(model.location.addr)"
  273. // } fail: { code, error in
  274. //
  275. // QSLLoading.hide()
  276. // self.view.toast(text: error)
  277. // }
  278. // }
  279. // }
  280. //绘制路线
  281. func mapView(_ mapView: MAMapView!, rendererFor overlay: MAOverlay!) -> MAOverlayRenderer! {
  282. if overlay.isKind(of: MAPolyline.self) {
  283. let polylineRender = MAPolylineRenderer.init(overlay: overlay)
  284. polylineRender?.lineWidth = 4
  285. polylineRender?.strokeColor = QSLColor.themeMainColor
  286. polylineRender?.fillColor = QSLColor.themeMainColor
  287. polylineRender?.lineJoinType = kMALineJoinRound
  288. polylineRender?.lineCapType = kMALineCapRound
  289. return polylineRender
  290. }
  291. return nil
  292. }
  293. // 绘制轨迹
  294. func drawLine() {
  295. var MATraceList: [MATraceLocation] = []
  296. guard let roadList = self.roadList else { return }
  297. for model in roadList {
  298. let location = MATraceLocation()
  299. location.speed = model.speed
  300. location.time = model.ts
  301. location.angle = model.bearing
  302. var loc = CLLocationCoordinate2D()
  303. loc.latitude = model.lat
  304. loc.longitude = model.lng
  305. location.loc = loc
  306. MATraceList.append(location)
  307. }
  308. self.roadManager.queryProcessedTrace(with: MATraceList, type: .aMap) { index, points in
  309. } finishCallback: { points, distance in
  310. print("轨迹纠偏success")
  311. // 纠偏成功添加纠偏后的折线
  312. if let points = points {
  313. var commonPolylineCoords = [CLLocationCoordinate2D](repeating: CLLocationCoordinate2D(), count: points.count)
  314. for i in 0..<points.count {
  315. commonPolylineCoords[i].latitude = points[i].latitude
  316. commonPolylineCoords[i].longitude = points[i].longitude
  317. }
  318. // 构造折线对象
  319. if let commonPolyline = MAPolyline(coordinates: &commonPolylineCoords, count: UInt(points.count)) {
  320. self.roadLine = commonPolyline
  321. // 在地图上添加折线对象
  322. self.roadMapView.add(self.roadLine)
  323. //调用划线后,调用下面方法,设置地图可视矩形的范围
  324. self.roadMapView.setVisibleMapRect(self.roadLine.boundingMapRect, edgePadding: UIEdgeInsets(top: 40, left: 40, bottom: 40, right: 40), animated: true)
  325. }
  326. // 添加起点图标
  327. if let startTrack = points.first {
  328. let startPoint = MAPointAnnotation()
  329. startPoint.coordinate = CLLocationCoordinate2D(latitude: startTrack.latitude, longitude: startTrack.longitude)
  330. startPoint.title = "起点"
  331. startPoint.subtitle = "road_begin_icon"
  332. self.beginAnnotation = startPoint
  333. }
  334. // 添加终点图标
  335. if let endTrack = points.last {
  336. let endPoint = MAPointAnnotation()
  337. endPoint.coordinate = CLLocationCoordinate2D(latitude: endTrack.latitude, longitude: endTrack.longitude)
  338. endPoint.title = "终点"
  339. endPoint.subtitle = "road_end_icon"
  340. self.endAnnotation = endPoint
  341. }
  342. // 设置地址
  343. if let startModel = self.roadList?.first,
  344. let endModel = self.roadList?.last {
  345. self.mainView.startAddressLabel.text = "起点:\(startModel.addr)"
  346. self.mainView.endAddressLabel.text = "终点:\(endModel.addr)"
  347. }
  348. // 添加起点和终点图标
  349. if let startPoint = self.beginAnnotation,
  350. let endPoint = self.endAnnotation {
  351. self.roadMapView.addAnnotation(startPoint)
  352. self.roadMapView.addAnnotation(endPoint)
  353. }
  354. }
  355. } failedCallback: { code, error in
  356. print("轨迹纠偏FailError: \(error ?? "")")
  357. // 纠偏失败添加原来的折线
  358. if let roadList = self.roadList {
  359. var commonPolylineCoords = [CLLocationCoordinate2D](repeating: CLLocationCoordinate2D(), count: roadList.count)
  360. for i in 0..<roadList.count {
  361. commonPolylineCoords[i].latitude = roadList[i].lat
  362. commonPolylineCoords[i].longitude = roadList[i].lng
  363. }
  364. // 构造折线对象
  365. if let commonPolyline = MAPolyline(coordinates: &commonPolylineCoords, count: UInt(roadList.count)) {
  366. self.roadLine = commonPolyline
  367. // 在地图上添加折线对象
  368. self.roadMapView.add(self.roadLine)
  369. //调用划线后,调用下面方法,设置地图可视矩形的范围
  370. self.roadMapView.setVisibleMapRect(self.roadLine.boundingMapRect, edgePadding: UIEdgeInsets(top: 40, left: 40, bottom: 40, right: 40), animated: true)
  371. }
  372. // 添加起点图标
  373. if let startTrack = roadList.first {
  374. let startPoint = MAPointAnnotation()
  375. startPoint.coordinate = CLLocationCoordinate2D(latitude: startTrack.lat, longitude: startTrack.lng)
  376. startPoint.title = "起点"
  377. startPoint.subtitle = "road_begin_icon"
  378. self.beginAnnotation = startPoint
  379. }
  380. // 添加终点图标
  381. if let endTrack = roadList.last {
  382. let endPoint = MAPointAnnotation()
  383. endPoint.coordinate = CLLocationCoordinate2D(latitude: endTrack.lat, longitude: endTrack.lng)
  384. endPoint.title = "终点"
  385. endPoint.subtitle = "road_end_icon"
  386. self.endAnnotation = endPoint
  387. }
  388. // 设置地址
  389. if let startTrack = roadList.first, let endTrack = roadList.last {
  390. self.mainView.startAddressLabel.text = "起点:\(startTrack.addr)"
  391. self.mainView.endAddressLabel.text = "终点:\(endTrack.addr)"
  392. }
  393. // 添加起点和终点注释
  394. if let startPoint = self.beginAnnotation,
  395. let endPoint = self.endAnnotation {
  396. self.roadMapView.addAnnotation(startPoint)
  397. self.roadMapView.addAnnotation(endPoint)
  398. }
  399. }
  400. }
  401. }
  402. }
  403. extension QSLRoadController: QSLRoadMainViewDelegate {
  404. func searchClickAction() {
  405. gravityInstance?.track(QSLGravityConst.road_search)
  406. self.requestRoad()
  407. }
  408. // 开始时间点击
  409. func startTimeClickAction() {
  410. self.startDatePicker.selectDate = self.startDate
  411. self.startDatePicker.show()
  412. self.startDatePicker.resultBlock = { [weak self] date, value in
  413. gravityInstance?.track(QSLGravityConst.road_time_confirm)
  414. self?.mainView.startTimeLabel.text = "开始时间:\(value ?? "")"
  415. if let date = date {
  416. self?.startDate = date
  417. // 获取目标时间(加24小时)
  418. var nextDay = date.addingTimeInterval(24 * 60 * 60)
  419. // 获取时间戳
  420. let startTime = date.timeIntervalSince1970
  421. let nowTime = self?.nowDate.timeIntervalSince1970
  422. // 判断时间差是否小于24小时
  423. if (nowTime ?? 0) - startTime < 24 * 60 * 60 {
  424. nextDay = self?.nowDate ?? Date() // 当前时间
  425. }
  426. self?.mainView.endTimeLabel.text = nextDay.toformatterTimeString(formatter: "结束时间:yyyy-MM-dd HH:mm")
  427. self?.endDate = nextDay
  428. self?.endDatePicker.selectDate = self?.endDate
  429. }
  430. }
  431. self.startDatePicker.cancelBlock = {
  432. gravityInstance?.track(QSLGravityConst.road_time_cancel)
  433. }
  434. }
  435. // 结束时间点击
  436. func endTimeClickAction() {
  437. self.endDatePicker.selectDate = self.endDate
  438. self.endDatePicker.show()
  439. self.endDatePicker.resultBlock = { [weak self] date, value in
  440. gravityInstance?.track(QSLGravityConst.road_time_confirm)
  441. self?.mainView.endTimeLabel.text = "结束时间:\(value ?? "")"
  442. if let date = date {
  443. self?.endDate = date
  444. }
  445. }
  446. self.endDatePicker.cancelBlock = {
  447. gravityInstance?.track(QSLGravityConst.road_time_cancel)
  448. }
  449. }
  450. }
  451. extension QSLRoadController {
  452. func initView() {
  453. self.view.addSubview(roadMapView)
  454. roadMapView.snp.makeConstraints { make in
  455. make.top.right.left.equalTo(0)
  456. make.edges.equalToSuperview()
  457. }
  458. self.view.addSubview(mainView)
  459. mainView.snp.makeConstraints { make in
  460. make.left.right.bottom.equalTo(0)
  461. make.height.equalTo(369.rpx)
  462. }
  463. self.view.addSubview(foldBtn)
  464. foldBtn.snp.makeConstraints { make in
  465. make.size.equalTo(CGSize(width: 20.rpx, height: 4.rpx))
  466. make.centerX.equalToSuperview()
  467. make.bottom.equalTo(mainView.snp.top).offset(-6.rpx)
  468. }
  469. self.view.addSubview(backButton)
  470. backButton.snp.makeConstraints { make in
  471. make.size.equalTo(CGSize(width: 50.rpx, height: 50.rpx))
  472. make.left.equalTo(0)
  473. make.top.equalTo(QSLConst.qsl_kStatusBarFrameH)
  474. }
  475. }
  476. }