map_util.dart 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import 'dart:math';
  2. import '../../flutter_map.dart';
  3. class MapUtil {
  4. MapUtil._();
  5. static double calculateLineLatLngDistance(LatLng p1, LatLng p2) {
  6. if (p1.latitude == null ||
  7. p1.longitude == null ||
  8. p2.latitude == null ||
  9. p2.longitude == null) {
  10. throw ArgumentError("Invalid coordinates");
  11. }
  12. return calculateLineDistance(
  13. p1.longitude!, p1.latitude!, p2.longitude!, p2.latitude!);
  14. }
  15. static double calculateLineDistance(double longitudeP1, double latitudeP1,
  16. double longitudeP2, double latitudeP2) {
  17. try {
  18. // 转为弧度
  19. double lon1 = longitudeP1 * (pi / 180.0);
  20. double lat1 = latitudeP1 * (pi / 180.0);
  21. double lon2 = longitudeP2 * (pi / 180.0);
  22. double lat2 = latitudeP2 * (pi / 180.0);
  23. double sinLon1 = sin(lon1);
  24. double sinLat1 = sin(lat1);
  25. double cosLon1 = cos(lon1);
  26. double cosLat1 = cos(lat1);
  27. double sinLon2 = sin(lon2);
  28. double sinLat2 = sin(lat2);
  29. double cosLon2 = cos(lon2);
  30. double cosLat2 = cos(lat2);
  31. // 三维向量表示
  32. List<double> v1 = [
  33. cosLat1 * cosLon1,
  34. cosLat1 * sinLon1,
  35. sinLat1,
  36. ];
  37. List<double> v2 = [
  38. cosLat2 * cosLon2,
  39. cosLat2 * sinLon2,
  40. sinLat2,
  41. ];
  42. // 计算向量差的模长
  43. double dx = v1[0] - v2[0];
  44. double dy = v1[1] - v2[1];
  45. double dz = v1[2] - v2[2];
  46. double chordLength = sqrt(dx * dx + dy * dy + dz * dz);
  47. // 球面线距离(地球平均半径约 6371000m)
  48. return asin(chordLength / 2.0) * 12742001.5798544;
  49. } catch (e) {
  50. print("Error in calculateLineDistance: $e");
  51. return 0.0;
  52. }
  53. }
  54. static String format(double distanceInMeters) {
  55. if (distanceInMeters < 1000) {
  56. return '${distanceInMeters.round()}m';
  57. } else {
  58. double km = distanceInMeters / 1000;
  59. String kmStr = km.toStringAsFixed(1);
  60. if (kmStr.endsWith('.0')) {
  61. kmStr = kmStr.substring(0, kmStr.length - 2); // 去掉 .0
  62. }
  63. return '${kmStr}km';
  64. }
  65. }
  66. }