diff --git a/lib/controller/functions/crud.dart b/lib/controller/functions/crud.dart index 942c17e..3b33f02 100644 --- a/lib/controller/functions/crud.dart +++ b/lib/controller/functions/crud.dart @@ -35,7 +35,7 @@ class CRUD { // print(response.body); var jsonData = jsonDecode(response.body); if (jsonData['status'] == 'success') { - // print(jsonData); + print(jsonData); return response.body; } diff --git a/lib/controller/home/captin/map_driver_controller.dart b/lib/controller/home/captin/map_driver_controller.dart index 3e83700..1ec1ff7 100644 --- a/lib/controller/home/captin/map_driver_controller.dart +++ b/lib/controller/home/captin/map_driver_controller.dart @@ -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().myLocation.latitude.toString(); - String driverLng = - Get.find().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? 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().myLocation.latitude, Get.find().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(); 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; diff --git a/lib/controller/home/map_passenger_controller.dart b/lib/controller/home/map_passenger_controller.dart index 7fb17de..c81eda4 100644 --- a/lib/controller/home/map_passenger_controller.dart +++ b/lib/controller/home/map_passenger_controller.dart @@ -737,7 +737,7 @@ class MapPassengerController extends GetxController { late String make; late String licensePlate; confirmRideForFirstDriver() async { - await getCarsLocationByPassenger(); + await getCarsLocationByPassengerAndReloadMarker(); await getNearestDriverByPassengerLocationAPIGOOGLE(); if (dataCarsLocationByPassenger != 'failure') { @@ -1064,7 +1064,7 @@ class MapPassengerController extends GetxController { late LatLng currentDriverLocation; late double headingList; - Future getCarsLocationByPassenger() async { + Future getCarsLocationByPassengerAndReloadMarker() async { // if (rideConfirm == false) { carsLocationByPassenger = []; LatLngBounds bounds = calculateBounds( @@ -1208,8 +1208,8 @@ class MapPassengerController extends GetxController { ['latitude']), double.parse(datadriverCarsLocationToPassengerAfterApplied['message'][0] ['longitude'])); - print('driver position $driverPosition') -; final driverAcceptedMarker = Marker( + print('driver position $driverPosition'); + final driverAcceptedMarker = Marker( markerId: const MarkerId('driverToPassengers'), position: driverPosition, rotation: double.parse( @@ -1667,7 +1667,7 @@ class MapPassengerController extends GetxController { //print('Reloading markers ($reloadCount)'); if (!rideConfirm) { reloadMarkers(); - }else{ + } else { runWhenRideIsBegin(); } @@ -1680,49 +1680,8 @@ class MapPassengerController extends GetxController { reloadMarkers() async { if (statusRide == 'wait') { - await getCarsLocationByPassenger(); + await getCarsLocationByPassengerAndReloadMarker(); await getNearestDriverByPassengerLocation(); - // markers.clear(); - - // update(); - // if (rideConfirm) { - - // } - // Add new markers - // Example: Add a marker for each item in a list - for (var item in carsLocationByPassenger) { - // for (var i = 0; i