map_location.dart 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import "codable.dart";
  2. class MapLocation implements Codable {
  3. final int? time;
  4. final String? address;
  5. final double latitude;
  6. final double longitude;
  7. final int? errorCode;
  8. final double? speed;
  9. final double? bearing;
  10. MapLocation({
  11. this.time,
  12. this.address,
  13. this.errorCode,
  14. this.speed,
  15. this.bearing,
  16. required this.latitude,
  17. required this.longitude,
  18. });
  19. @override
  20. Map<String, dynamic> toJson() {
  21. return {
  22. 'time': time,
  23. 'address': address,
  24. 'latitude': latitude,
  25. 'longitude': longitude,
  26. 'errorCode': errorCode,
  27. 'speed': speed,
  28. 'bearing': bearing,
  29. };
  30. }
  31. factory MapLocation.fromJson(Map<String, dynamic> map) {
  32. return MapLocation(
  33. time: map['time'],
  34. address: map['address'],
  35. latitude: _parseDouble(map['latitude']),
  36. longitude: _parseDouble(map['longitude']),
  37. errorCode: map['errorCode'],
  38. speed: _parseDouble(map['speed']),
  39. bearing: _parseDouble(map['bearing']),
  40. );
  41. }
  42. // 将任何数值类型(包括整数)强制转换为double
  43. static double _parseDouble(dynamic value) {
  44. if (value == null) return 0.0;
  45. if (value is double) return value;
  46. if (value is int) return value.toDouble();
  47. if (value is String) return double.tryParse(value) ?? 0.0;
  48. return 0.0;
  49. }
  50. @override
  51. String toString() {
  52. return '{time: $time, address: $address, latitude: $latitude, longitude: $longitude, errorCode: $errorCode, speed: $speed, bearing: $bearing}';
  53. }
  54. }