This commit is contained in:
Hamza Aleghwairyeen
2024-04-02 17:07:25 +03:00
parent 417b8ffd94
commit fddb509883
4 changed files with 116 additions and 210 deletions

View File

@@ -110,7 +110,7 @@ class MapDriverController extends GetxController {
update();
// Set up a timer or interval to trigger the marker update every 3 seconds.
timer = Timer.periodic(const Duration(seconds: 2), (_) {
timer = Timer.periodic(const Duration(seconds: 1), (_) {
updateMarker();
});
}
@@ -135,7 +135,7 @@ class MapDriverController extends GetxController {
super.dispose();
}
void openGoogleMapFromDriverToPassenger() async {
Future openGoogleMapFromDriverToPassenger() async {
var endLat = latLngpassengerLocation.latitude;
var endLng = latLngpassengerLocation.longitude;
@@ -151,21 +151,6 @@ class MapDriverController extends GetxController {
}
}
void checkIsDriverNearPassenger() async {
if (isDriverNearPassengerStart) {
Timer.periodic(const Duration(seconds: 3), (timer) {
String driverLat =
Get.find<LocationController>().myLocation.latitude.toString();
String driverLng =
Get.find<LocationController>().myLocation.longitude.toString();
// Replace "passengerLat" and "passengerLng" with the actual passenger's location
String passengerLat = passengerLocation; // Set the passenger's latitude
String passengerLng = ""; // Set the passenger's longitude
});
}
}
void clearPolyline() {
polyLines = [];
polyLinesDestination = [];
@@ -181,33 +166,7 @@ class MapDriverController extends GetxController {
}
void startTimerToShowPassengerInfoWindowFromDriver() async {
// for (int i = 0;
// i <= progressTimerToShowPassengerInfoWindowFromDriver;
// i++) {
// await Future.delayed(const Duration(seconds: 1));
// if (canelString != 'Cancel') {
// cancelCheckRidefromPassenger();
// progress = i / progressTimerToShowPassengerInfoWindowFromDriver;
// remainingTimeToShowPassengerInfoWindowFromDriver =
// progressTimerToShowPassengerInfoWindowFromDriver - i;
// if (remainingTimeToShowPassengerInfoWindowFromDriver == 0) {
isPassengerInfoWindow = true;
// print(isPassengerInfoWindow);
update();
startTimerToShowDriverToPassengerDuration();
// }
// print(isPassengerInfoWindow);
// print(remainingTimeToShowPassengerInfoWindowFromDriver);
// update();
// } else {
// Get.off(HomeCaptain());
// }
// }
}
String stringRemainingTimeToPassenger = '';
void startTimerToShowDriverToPassengerDuration() async {
for (int i = 0; i <= int.parse(durationToPassenger); i++) {
await Future.delayed(const Duration(seconds: 1));
progressToPassenger = i / int.parse(durationToPassenger);
@@ -227,8 +186,12 @@ class MapDriverController extends GetxController {
update();
}
// update();
// startTimerToShowDriverToPassengerDuration();
}
String stringRemainingTimeToPassenger = '';
String stringRemainingTimeWaitingPassenger = '';
void startTimerToShowDriverWaitPassengerDuration() async {
@@ -270,7 +233,7 @@ class MapDriverController extends GetxController {
box.read(BoxName.name).toString(),
tokenPassenger);
if (box.read(BoxName.googlaMapApp) == true) {
openGoogleMapFromDriverToPassenger();
await openGoogleMapFromDriverToPassenger();
}
}
@@ -316,16 +279,6 @@ class MapDriverController extends GetxController {
Position? currentPosition;
calculateDistanceAndTimeSPEEDOMETER() async {
/* todo
save to sql
calculate distance and duration
get from sql
update ui for totla results
*/
}
startRideFromDriver() async {
double _distance =
await calculateDistanceBetweenDriverAndPassengerLocation();
@@ -400,47 +353,31 @@ update ui for totla results
double speedoMeter = 0;
void updateLocation() async {
StreamSubscription<Position>? locationSubscription;
try {
LatLng? latestPosition; // Initialize outside the loop
for (var i = 0; i < remainingTimeTimerRideBegin; i++) {
await Future.delayed(const Duration(seconds: 2));
locationSubscription =
Geolocator.getPositionStream().listen((Position position) {
latestPosition = position as LatLng?; // Update latest position
await Future.delayed(const Duration(seconds: 1));
// Calculate distance using the latest position
double distance = calculateDistanceInMeter(
currentPosition as LatLng, latestPosition!);
speedoMeter = distance + speedoMeter;
print('distance is $distance');
print('SpedoMeter is $speedoMeter');
currentPosition = position;
// Update camera position on the map
mapController!.animateCamera(
CameraUpdate.newCameraPosition(
CameraPosition(
target: myLocation,
zoom: 17, // Adjust zoom level as needed
),
mapController!.animateCamera(
CameraUpdate.newCameraPosition(
CameraPosition(
target: myLocation,
zoom: 17, // Adjust zoom level as needed
),
);
});
),
);
// });
update();
}
// Stop listening after ride finishes
if (!isRideBegin) {
locationSubscription?.cancel();
}
if (!isRideBegin) {}
} catch (error) {
debugPrint('Error listening to GPS: $error');
// Handle GPS errors gracefully
}
// Periodically call updateLocation again
await Future.delayed(const Duration(seconds: 2));
await Future.delayed(const Duration(seconds: 1));
updateLocation();
}
@@ -501,59 +438,94 @@ update ui for totla results
Get.find<LocationController>().myLocation.latitude,
Get.find<LocationController>().myLocation.longitude,
);
// if (distanceToDestination < 50) {
isRideFinished = true;
isRideStarted = false;
isPriceWindow = false;
if (carType == 'Comfort' || carType == 'Free Ride') {
if (carType != 'Comfort' || carType != 'Free Ride') {
if (distanceToDestination < 50) {
isRideFinished = true;
isRideStarted = false;
isPriceWindow = false;
box.write(BoxName.statusDriverLocation, 'off');
// changeRideToBeginToPassenger();
await CRUD().post(link: AppLink.updateRides, payload: {
'id': rideId,
'rideTimeFinish': DateTime.now().toString(),
'status': 'Finished'
});
print('walletChecked is $walletChecked');
if (walletChecked == 'true') {
await CRUD().post(link: AppLink.addPassengersWallet, payload: {
'passenger_id': passengerId,
'balance': ((-1) * double.parse(paymentAmount)).toString()
});
}
print('passengerWalletBurc bef ${double.parse(passengerWalletBurc)}');
if (double.parse(passengerWalletBurc) < 0) {
await CRUD().post(link: AppLink.addPassengersWallet, payload: {
'passenger_id': passengerId,
'balance': ((-1) * double.parse(passengerWalletBurc)).toString()
});
print(
'passengerWalletBurc aft ${double.parse(passengerWalletBurc)}');
}
Future.delayed(const Duration(milliseconds: 300));
FirebaseMessagesController().sendNotificationToPassengerToken(
'Driver Finish Trip',
'you will pay to Driver'.tr + ' $totalCost \$'.tr,
tokenPassenger,
[
box.read(BoxName.driverID),
rideId,
box.read(BoxName.tokenDriver),
],
);
} else {
Get.defaultDialog(
title: 'You don\'t arrive destenation yet .'.tr,
middleText: '',
confirm: MyElevatedButton(
title: 'Ok'.tr,
onPressed: () {
Get.back();
}));
}
} else {
totalCost = price.toStringAsFixed(2);
paymentAmount = totalCost;
// update();
}
box.write(BoxName.statusDriverLocation, 'off');
// changeRideToBeginToPassenger();
await CRUD().post(link: AppLink.updateRides, payload: {
'id': rideId,
'rideTimeFinish': DateTime.now().toString(),
'status': 'Finished'
});
print('walletChecked is $walletChecked');
if (walletChecked == 'true') {
await CRUD().post(link: AppLink.addPassengersWallet, payload: {
'passenger_id': passengerId,
'balance': ((-1) * double.parse(paymentAmount)).toString()
box.write(BoxName.statusDriverLocation, 'off');
// changeRideToBeginToPassenger();
await CRUD().post(link: AppLink.updateRides, payload: {
'id': rideId,
'rideTimeFinish': DateTime.now().toString(),
'status': 'Finished'
});
print('walletChecked is $walletChecked');
if (walletChecked == 'true') {
await CRUD().post(link: AppLink.addPassengersWallet, payload: {
'passenger_id': passengerId,
'balance': ((-1) * double.parse(paymentAmount)).toString()
});
}
print('passengerWalletBurc bef ${double.parse(passengerWalletBurc)}');
if (double.parse(passengerWalletBurc) < 0) {
await CRUD().post(link: AppLink.addPassengersWallet, payload: {
'passenger_id': passengerId,
'balance': ((-1) * double.parse(passengerWalletBurc)).toString()
});
print('passengerWalletBurc aft ${double.parse(passengerWalletBurc)}');
}
Future.delayed(const Duration(milliseconds: 300));
FirebaseMessagesController().sendNotificationToPassengerToken(
'Driver Finish Trip',
'you will pay to Driver'.tr + ' $totalCost \$'.tr,
tokenPassenger,
[
box.read(BoxName.driverID),
rideId,
box.read(BoxName.tokenDriver),
],
);
}
print('passengerWalletBurc bef ${double.parse(passengerWalletBurc)}');
if (double.parse(passengerWalletBurc) < 0) {
await CRUD().post(link: AppLink.addPassengersWallet, payload: {
'passenger_id': passengerId,
'balance': ((-1) * double.parse(passengerWalletBurc)).toString()
});
print('passengerWalletBurc aft ${double.parse(passengerWalletBurc)}');
}
Future.delayed(const Duration(milliseconds: 300));
FirebaseMessagesController().sendNotificationToPassengerToken(
'Driver Finish Trip',
'you will pay to Driver'.tr + ' $totalCost \$'.tr,
tokenPassenger,
[
box.read(BoxName.driverID),
rideId,
box.read(BoxName.tokenDriver),
],
);
// } else {
// Get.defaultDialog(
// title: 'You don\'t arrive destenation yet .'.tr,
// middleText: '',
// confirm: MyElevatedButton(
// title: 'Ok'.tr,
// onPressed: () {
// Get.back();
// }));
// }
// add wallet from passenger from driver
Get.to(() => RatePassenger(), arguments: {
'passengerId': passengerId,
@@ -644,41 +616,15 @@ update ui for totla results
double recentAngelToMarker = 0;
double speed = 0;
void updateMarker() async {
// Remove the existing marker with the ID `MyLocation`.
markers.remove(MarkerId('MyLocation'));
markers.remove( MarkerId('MyLocation'));
// Add a new marker with the ID `MyLocation` at the current location of the user.
LocationController locationController = Get.find<LocationController>();
myLocation = locationController.myLocation;
final previousLocationOfDrivers = await sql.getCustomQuery('''SELECT
*
FROM
${TableName.rideLocation}
WHERE
order_id = $rideId
ORDER BY
created_at DESC
LIMIT
1''');
print(previousLocationOfDrivers);
//get from sql
if (previousLocationOfDrivers.isNotEmpty) {
var lat = double.parse(previousLocationOfDrivers[0]['lat']);
var lng = double.parse(previousLocationOfDrivers[0]['lng']);
LatLng prev = LatLng(lat, lng);
// recentDistanceToDash =
// calculateDistanceBetweenLocations(prev, myLocation);
print('recentAngelToMarker $recentAngelToMarker');
print('recentDistanceToDash $recentDistanceToDash');
}
sql.insertData({
'order_id': rideId,
'created_at': DateTime.now().microsecondsSinceEpoch.toString(),
'lat': myLocation.latitude.toString(),
'lng': myLocation.longitude.toString(),
}, TableName.rideLocation);
markers.add(
Marker(
markerId: MarkerId('MyLocation'.tr),
@@ -947,6 +893,7 @@ LIMIT
addCustomStartIcon();
addCustomEndIcon();
// updateMarker();
updateLocation();
startTimerToShowPassengerInfoWindowFromDriver();
durationToAdd = Duration(seconds: int.parse(duration));
hours = durationToAdd.inHours;