owntracks-viewer/lib/util.dart
2024-03-14 20:50:30 +01:00

99 lines
3.0 KiB
Dart

import 'dart:math';
String formatDuration(Duration duration) {
final days = duration.inDays;
final hours = duration.inHours.remainder(24);
final minutes = duration.inMinutes.remainder(60);
final seconds = duration.inSeconds.remainder(60);
String plural(int thing) => thing == 1 ? '' : 's';
if (days > 0) {
return '$days day${plural(days)}, $hours hour${plural(hours)}';
} else if (hours > 0) {
return '$hours hour${plural(hours)}, $minutes minute${plural(minutes)}';
} else if (minutes > 0) {
return '$minutes minute${plural(minutes)}, $seconds second${plural(seconds)}';
} else {
return '$seconds second${plural(seconds)}';
}
}
String formatDistance(int distanceInMeters) {
if (distanceInMeters < 1000) {
// If the distance is less than 1 kilometer, display it in meters.
return '${distanceInMeters}m';
} else {
// If the distance is 1 kilometer or more, display it in kilometers and meters.
final kilometers = distanceInMeters ~/ 1000; // Integer division to get whole kilometers.
final meters = distanceInMeters % 1000; // Remainder to get the remaining meters.
if (meters == 0) {
// If there are no remaining meters, display only kilometers.
return '${kilometers}km';
} else {
// If there are remaining meters, display both kilometers and meters.
return '${kilometers}km ${meters}m';
}
}
}
double degreesToRadians(double degrees) {
return degrees * (pi / 180);
}
double radiansToDegrees(double radians) {
return radians * (180 / pi);
}
double bearingBetween(double lat1, double lon1, double lat2, double lon2) {
var dLon = degreesToRadians(lon2 - lon1);
var y = sin(dLon) * cos(degreesToRadians(lat2));
var x = cos(degreesToRadians(lat1)) * sin(degreesToRadians(lat2)) -
sin(degreesToRadians(lat1)) * cos(degreesToRadians(lat2)) * cos(dLon);
var angle = atan2(y, x);
return (radiansToDegrees(angle) + 360) % 360;
}
double distanceBetween(
double lat1, double lon1, double lat2, double lon2, String unit) {
const earthRadius = 6371; // in km
// assuming earth is a perfect sphere(it's not)
// Convert degrees to radians
final lat1Rad = degreesToRadians(lat1);
final lon1Rad = degreesToRadians(lon1);
final lat2Rad = degreesToRadians(lat2);
final lon2Rad = degreesToRadians(lon2);
final dLat = lat2Rad - lat1Rad;
final dLon = lon2Rad - lon1Rad;
// Haversine formula
final a = pow(sin(dLat / 2), 2) +
cos(lat1Rad) * cos(lat2Rad) * pow(sin(dLon / 2), 2);
final c = 2 * atan2(sqrt(a), sqrt(1 - a));
final distance = earthRadius * c;
return toRequestedUnit(unit, distance);
// return distance; // in km
}
double toRequestedUnit(String unit, double distanceInKm) {
switch (unit) {
case 'kilometers':
return distanceInKm;
case 'meters':
return distanceInKm * 1000;
case 'miles':
return (distanceInKm * 1000) / 1609.344;
case 'yards':
return distanceInKm * 1093.61;
case '':
return distanceInKm;
}
return distanceInKm;
}