track_controller.dart 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. import 'package:flutter/cupertino.dart';
  2. import 'package:flutter/material.dart';
  3. import 'package:flutter_cupertino_datetime_picker/flutter_cupertino_datetime_picker.dart';
  4. import 'package:flutter_map/flutter_map.dart';
  5. import 'package:get/get.dart';
  6. import 'package:get/get_core/src/get_main.dart';
  7. import 'package:injectable/injectable.dart';
  8. import 'package:location/base/base_controller.dart';
  9. import 'package:location/data/bean/location_info.dart';
  10. import 'package:location/data/consts/constants.dart';
  11. import 'package:location/data/repositories/friends_repository.dart';
  12. import 'package:location/data/repositories/track_repository.dart';
  13. import 'package:location/dialog/loading_dialog.dart';
  14. import 'package:location/handler/error_handler.dart';
  15. import 'package:location/module/track/track_util.dart';
  16. import 'package:location/resource/string.gen.dart';
  17. import 'package:location/utils/atmob_log.dart';
  18. import 'package:location/utils/common_expand.dart';
  19. import 'package:location/utils/toast_util.dart';
  20. import 'package:sliding_sheet2/sliding_sheet2.dart';
  21. import '../../data/bean/atmob_track_point.dart';
  22. import '../../data/bean/user_info.dart';
  23. import '../../utils/date_util.dart';
  24. import '../../utils/location_convert_marker_util.dart';
  25. import '../../utils/pair.dart';
  26. @injectable
  27. class TrackController extends BaseController
  28. with GetSingleTickerProviderStateMixin {
  29. final int errorQueryOriginalDataEmpty = 10; //查询原始数据集为空
  30. final int errorQueryOriginalTooFew = 11; //查询原始数据集少于2点
  31. final Rxn<UserInfo> _userInfo = Rxn<UserInfo>();
  32. UserInfo? get userInfo => _userInfo.value;
  33. final MapController mapController = MapController();
  34. final Rxn<DateTime> _trackStartTime = Rxn<DateTime>();
  35. final Rxn<DateTime> _trackEndTime = Rxn<DateTime>();
  36. DateTime? get trackStartTime => _trackStartTime.value;
  37. DateTime? get trackEndTime => _trackEndTime.value;
  38. SheetController sheetController = SheetController();
  39. final Rxn<String> _startAddress = Rxn<String>();
  40. final Rxn<String> _endAddress = Rxn<String>();
  41. String? get startAddress => _startAddress.value;
  42. String? get endAddress => _endAddress.value;
  43. final Duration maxDuration = Duration(days: 1);
  44. final String timeFormat = "yyyy年-MM月-dd日 HH时:mm分";
  45. late TabController tabController;
  46. final RxInt _currentIndex = 0.obs;
  47. int get currentIndex => _currentIndex.value;
  48. final Rxn<LocationInfo> _currentLocation = Rxn<LocationInfo>();
  49. LocationInfo? get currentLocation => _currentLocation.value;
  50. List<LatLng>? points;
  51. final TrackRepository trackRepository;
  52. final FriendsRepository friendsRepository;
  53. TrackController(this.trackRepository, this.friendsRepository);
  54. @override
  55. void onInit() {
  56. final param = Get.arguments;
  57. if (param is UserInfo) {
  58. _userInfo.value = param;
  59. }
  60. tabController = TabController(
  61. length: 2, vsync: this, initialIndex: _currentIndex.value);
  62. tabController.addListener(_handleTabChange);
  63. _initTime();
  64. _onCurrentLocationQuery(showLoading: false);
  65. }
  66. @override
  67. void onReady() {
  68. super.onReady();
  69. sheetController.expand();
  70. }
  71. void _handleTabChange() {
  72. if (tabController.indexIsChanging) return;
  73. _currentIndex.value = tabController.index;
  74. if (tabController.index == 0) {
  75. _showTrack();
  76. } else if (tabController.index == 1) {
  77. _showCurrentLocation();
  78. }
  79. }
  80. void _initTime() {
  81. //开始时间往前推一天
  82. _trackStartTime.value = DateUtil.getNow(subtract: Duration(days: 1));
  83. _trackEndTime.value = DateUtil.getNow();
  84. }
  85. void back() {
  86. Get.back();
  87. }
  88. void onTrackStartTimeClick(BuildContext context) {
  89. DatePicker.showDatePicker(context,
  90. locale: DateTimePickerLocale.zh_cn,
  91. initialDateTime: _trackStartTime.value,
  92. dateFormat: timeFormat, onConfirm: (dateTime, selectedIndex) {
  93. if (trackEndTime != null &&
  94. DateUtil.isTimeRangeExceed(dateTime, trackEndTime!, maxDuration)) {
  95. ToastUtil.show(StringName.trackChooseTimeError);
  96. _trackEndTime.value = dateTime.add(maxDuration);
  97. }
  98. _trackStartTime.value = dateTime;
  99. });
  100. }
  101. void onTrackEndTimeClick(BuildContext context) {
  102. DatePicker.showDatePicker(context,
  103. locale: DateTimePickerLocale.zh_cn,
  104. initialDateTime: _trackEndTime.value,
  105. dateFormat: timeFormat, onConfirm: (dateTime, selectedIndex) {
  106. if (trackStartTime != null &&
  107. DateUtil.isTimeRangeExceed(dateTime, trackStartTime!, maxDuration)) {
  108. ToastUtil.show(StringName.trackChooseTimeError);
  109. _trackStartTime.value = dateTime.subtract(maxDuration);
  110. }
  111. _trackEndTime.value = dateTime;
  112. });
  113. }
  114. void onTrackQueryClick() {
  115. if (currentIndex == 0) {
  116. _onTrackQuery();
  117. } else {
  118. _onCurrentLocationQuery();
  119. }
  120. }
  121. void _onCurrentLocationQuery({bool showLoading = true}) {
  122. if (userInfo == null) {
  123. return;
  124. }
  125. if (showLoading) LoadingDialog.show(StringName.trackLoadingTxt);
  126. friendsRepository
  127. .getUserInfoFromId(userInfo!.id, isVirtual: userInfo!.virtual)
  128. .then((userInfo) {
  129. LoadingDialog.hide();
  130. _currentLocation.value = userInfo?.lastLocation.value;
  131. _showCurrentLocation();
  132. }).catchError((error) {
  133. debugPrint("error: $error");
  134. ErrorHandler.toastError(error);
  135. });
  136. }
  137. void _onTrackQuery() {
  138. if (trackStartTime == null || trackEndTime == null || userInfo == null) {
  139. return;
  140. }
  141. LoadingDialog.show(StringName.trackLoadingTxt);
  142. _startAddress.value = '';
  143. _endAddress.value = '';
  144. Future.value().then((_) {
  145. if (userInfo?.virtual == true) {
  146. return trackRepository.queryVirtualTrack();
  147. } else {
  148. return trackRepository.queryTrack(
  149. startTime: trackStartTime?.millisecondsSinceEpoch,
  150. endTime: trackEndTime?.millisecondsSinceEpoch,
  151. userId: userInfo?.id);
  152. }
  153. }).map((trackResponse) {
  154. final pointsList = trackResponse.trackPoints;
  155. if (pointsList == null || pointsList.isEmpty) {
  156. throw TrackQueryException(errorQueryOriginalDataEmpty);
  157. }
  158. if (pointsList.length < 2) {
  159. throw TrackQueryException(errorQueryOriginalTooFew);
  160. }
  161. if (userInfo?.virtual == true) {
  162. int nowMill = DateUtil.getNow().millisecondsSinceEpoch;
  163. int firstMill = pointsList.first.time;
  164. int differ = nowMill - firstMill;
  165. pointsList.first.time = nowMill;
  166. for (var element in pointsList) {
  167. element.time = element.time + differ;
  168. }
  169. }
  170. return pointsList;
  171. }).then((pointsList) async {
  172. final list = TrackUtil.points2TraceLocation(pointsList);
  173. List<LatLng>? convertList;
  174. try {
  175. convertList = await FlutterMap.queryProcessedTrace(
  176. lineID: pointsList.hashCode, locations: list);
  177. } catch (e) {
  178. AtmobLog.e("TrackController", "queryProcessedTrace error: $e");
  179. }
  180. if (convertList == null || convertList.isEmpty) {
  181. //轨迹纠偏失败,使用原始数据
  182. convertList = TrackUtil.traceLocation2LatLng(list);
  183. }
  184. return Pair(pointsList, convertList);
  185. }).then((pair) {
  186. LoadingDialog.hide();
  187. points = pair.second;
  188. _showTrack();
  189. _setStartAndEndAddress(start: pair.first.first, end: pair.first.last);
  190. }).catchError((error) {
  191. LoadingDialog.hide();
  192. if (error is TrackQueryException) {
  193. } else {
  194. ErrorHandler.toastError(error);
  195. }
  196. });
  197. }
  198. @override
  199. void onClose() {
  200. super.onClose();
  201. tabController.dispose();
  202. }
  203. void _setStartAndEndAddress(
  204. {required AtmobTrackPoint start, required AtmobTrackPoint end}) {
  205. _startAddress.value = start.addr;
  206. _endAddress.value = end.addr;
  207. }
  208. void _showCurrentLocation() {
  209. mapController.clear();
  210. if (currentLocation == null || userInfo == null) {
  211. return;
  212. }
  213. mapController.updateOrAddMarker(Marker(
  214. id: userInfo!.id,
  215. markerName: userInfo!.getUserNickName(),
  216. longitude: userInfo!.lastLocation.value?.longitude,
  217. latitude: userInfo!.lastLocation.value?.latitude,
  218. markerType: userInfo!.isMine == true
  219. ? MarkerType.traceEndMinePoint
  220. : MarkerType.traceEndFriendPoint,
  221. ));
  222. mapController.animateCamera(CameraPosition(
  223. latitude: currentLocation!.latitude,
  224. longitude: currentLocation!.longitude,
  225. zoom: 18));
  226. }
  227. void _showTrack() {
  228. mapController.clear();
  229. if (points == null || points!.length < 2) {
  230. return;
  231. }
  232. mapController.addPolyline(points!,
  233. mapPadding:
  234. MapPadding(left: 50, top: 100, right: 50, bottom: Get.height / 2));
  235. mapController.updateOrAddMarker(Marker(
  236. id: Constants.traceStartId,
  237. markerName: '',
  238. longitude: points!.first.longitude,
  239. latitude: points!.first.latitude,
  240. markerType: MarkerType.traceStartPoint));
  241. mapController.updateOrAddMarker(Marker(
  242. id: Constants.traceEndId,
  243. markerName: userInfo?.getUserNickName() ?? '',
  244. longitude: points!.last.longitude,
  245. latitude: points!.last.latitude,
  246. markerType: userInfo?.isMine == true
  247. ? MarkerType.traceEndMinePoint
  248. : MarkerType.traceEndFriendPoint));
  249. //显示起点标记
  250. // drawMarker();
  251. //显示终点标记
  252. }
  253. }
  254. class TrackQueryException implements Exception {
  255. final int code;
  256. TrackQueryException(this.code);
  257. }