geolocator_helper.dart 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import 'dart:async';
  2. import 'package:geolocation/geolocation.dart';
  3. import 'package:geolocation/models/position.dart';
  4. import 'package:get/get.dart';
  5. import 'index.dart';
  6. typedef GeolocatorHelperCallback = void Function(GeoPosition result);
  7. /// 定位工具类
  8. class GeolocatorHelper {
  9. // 是否单次定位 单次定位 返回结果的时候直接停止
  10. final bool isSingleLocation;
  11. final GeolocatorHelperCallback callback;
  12. StreamSubscription<GeoPosition>? _positionStream;
  13. GeolocatorHelper({required this.callback, this.isSingleLocation = false});
  14. /// 关闭定位
  15. Future<void> stopLocation() async {
  16. await _positionStream?.cancel();
  17. _positionStream = null;
  18. }
  19. /// 开始定位
  20. Future<void> startLocation() async {
  21. bool permission = await O2Utils.locationPermission();
  22. if (!permission) {
  23. OLogger.e('没有权限,无法定位!');
  24. Loading.showError('attendance_location_permission_not_allow'.tr);
  25. return;
  26. }
  27. if (isSingleLocation) {
  28. _singleLocation();
  29. } else {
  30. _seriesLocation();
  31. }
  32. }
  33. /// 计算距离
  34. double distanceInMeters(double startLatitude, double startLongitude, double endLatitude, double endLongitude) {
  35. GeoPosition start = GeoPosition(latitude: startLatitude, longitude: startLongitude);
  36. GeoPosition end = GeoPosition(latitude: endLatitude, longitude: endLongitude);
  37. double distanceInMeters = Geolocation.distanceBetween(start, end);
  38. if (distanceInMeters < 0) {
  39. distanceInMeters = 0 - distanceInMeters;
  40. }
  41. return distanceInMeters;
  42. }
  43. /// 单次定位
  44. Future<void> _singleLocation() async {
  45. final position = await Geolocation.getCurrentPosition();
  46. if (position != null) {
  47. callback(position);
  48. OLogger.i('单次定位: $position');
  49. }
  50. }
  51. /// 连续定位
  52. Future<void> _seriesLocation() async {
  53. await stopLocation();
  54. _positionStream = Geolocation.getPositionStream().listen((position) {
  55. callback(position);
  56. OLogger.d(
  57. "定位信息, longitude: ${position.longitude} , latitude: ${position.latitude}, address:${position.address}");
  58. });
  59. OLogger.i('开始连续定位');
  60. }
  61. }