This commit is contained in:
Hamza-Ayed
2024-03-21 02:09:52 +03:00
parent ad062d9ad7
commit 045f7e20f0
46 changed files with 2767 additions and 877 deletions

View File

@@ -58,7 +58,7 @@ class HomeCaptainController extends GetxController {
isActive = !isActive;
if (isActive) {
if (double.parse(totalPoints) > -500) {
if (double.parse(totalPoints) > -300) {
locationController.startLocationUpdates();
activeStartTime = DateTime.now();
activeTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
@@ -105,7 +105,7 @@ class HomeCaptainController extends GetxController {
await sql.getCustomQuery(customQuery);
countRefuse = results[0]['count'].toString();
update();
if (int.parse(countRefuse) > 3 || double.parse(totalPoints) <= -500) {
if (int.parse(countRefuse) > 3 || double.parse(totalPoints) <= -300) {
print('total point is $totalPoints');
locationController.stopLocationUpdates();
activeStartTime = null;
@@ -202,8 +202,8 @@ class HomeCaptainController extends GetxController {
getAllPayment();
startPeriodicExecution();
onMapCreated(mapHomeCaptaiController);
getRefusedOrderByCaptain();
totalPoints = Get.find<CaptainWalletController>().totalPoints;
getRefusedOrderByCaptain();
// LocationController().getLocation();
super.onInit();
}

View File

@@ -1,6 +1,8 @@
import 'dart:async';
import 'dart:convert';
import 'dart:math' as math;
import 'dart:math' show cos;
import 'package:SEFER/constant/table_names.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:get/get.dart';
@@ -49,10 +51,10 @@ class MapDriverController extends GetxController {
late String duration;
late String totalCost;
late String distance;
late String name;
late String email;
late String passengerName;
late String passengerEmail;
late String totalPassenger;
late String phone;
late String passengerPhone;
late String rideId;
late String isHaveSteps;
late String paymentAmount;
@@ -72,6 +74,7 @@ class MapDriverController extends GetxController {
bool isdriverWaitTimeEnd = false;
bool isRideFinished = false;
bool isRideStarted = false;
bool isPriceWindow = false;
double passengerInfoWindow = Get.height * .39;
double driverEndPage = 100;
double progress = 0;
@@ -177,29 +180,29 @@ 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;
// 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());
}
}
// if (remainingTimeToShowPassengerInfoWindowFromDriver == 0) {
isPassengerInfoWindow = true;
// print(isPassengerInfoWindow);
update();
startTimerToShowDriverToPassengerDuration();
// }
// print(isPassengerInfoWindow);
// print(remainingTimeToShowPassengerInfoWindowFromDriver);
// update();
// } else {
// Get.off(HomeCaptain());
// }
// }
}
String stringRemainingTimeToPassenger = '';
@@ -312,6 +315,16 @@ class MapDriverController extends GetxController {
Position? currentPosition;
calculateDistanceAndTimeSPEEDOMETER() async {
/* todo
save to sql
calculate distance and duration
get from sql
update ui for totla results
*/
}
void startRideFromDriver() async {
double _distance =
await calculateDistanseBetweenDriverAndPassengerLocation();
@@ -371,14 +384,34 @@ class MapDriverController extends GetxController {
}
}
calcualateDistsanceInMetet(LatLng prev, LatLng current) async {
double distance2 = Geolocator.distanceBetween(
prev.latitude,
prev.longitude,
current.latitude,
current.longitude,
);
return distance2;
}
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
// Calculate distance using the latest position
double distance = calcualateDistsanceInMetet(
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(
@@ -466,6 +499,7 @@ class MapDriverController extends GetxController {
// if (distanceToDestination < 50) {
isRideFinished = true;
isRideStarted = false;
isPriceWindow = false;
box.write(BoxName.statusDriverLocation, 'off');
// changeRideToBeginToPassenger();
@@ -500,11 +534,7 @@ class MapDriverController extends GetxController {
box.read(BoxName.tokenDriver),
],
);
Get.to(() => RatePassenger(), arguments: {
'rideId': rideId,
'passengerId': passengerId,
'driverId': driverId
});
// } else {
// Get.defaultDialog(
// title: 'You don\'t arrive destenation yet .'.tr,
@@ -516,7 +546,7 @@ class MapDriverController extends GetxController {
// }));
// }
// add wallet from passenger from driver
Get.to(() => RatePassenger());
// Get.back();
}
@@ -576,19 +606,76 @@ class MapDriverController extends GetxController {
}
}
void updateMarker() {
double calculateDistanceBetweenLocations(LatLng start, LatLng end) {
double startLat = start.latitude * math.pi / 180;
double startLon = start.longitude * math.pi / 180;
double endLat = end.latitude * math.pi / 180;
double endLon = end.longitude * math.pi / 180;
double dLat = endLat - startLat;
double dLon = endLon - startLon;
double a = math.pow(math.sin(dLat / 2), 2) +
math.cos(startLat) * math.cos(endLat) * math.pow(math.sin(dLon / 2), 2);
double c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a));
double distance = 6371000 * c; // Distance in meters
return distance;
}
double calculateAngleBetweenLocations(LatLng start, LatLng end) {
double startLat = start.latitude * math.pi / 180;
double startLon = start.longitude * math.pi / 180;
double endLat = end.latitude * math.pi / 180;
double endLon = end.longitude * math.pi / 180;
double dLon = endLon - startLon;
double y = math.sin(dLon) * cos(endLat);
double x = cos(startLat) * math.sin(endLat) -
math.sin(startLat) * cos(endLat) * cos(dLon);
double angle = math.atan2(y, x);
double angleDegrees = angle * 180 / math.pi;
return angleDegrees;
}
double recentDistanceToDash = 0;
double recentAngelToMarker = 0;
void updateMarker() async {
// Remove the existing marker with the ID `MyLocation`.
markers.remove(MarkerId('MyLocation'.tr));
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.carLocations} where order_id =$rideId Order by created_at DESC limit 1');
//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);
recentAngelToMarker = calculateAngleBetweenLocations(prev, myLocation);
recentDistanceToDash =
calculateDistanceBetweenLocations(prev, myLocation);
}
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),
position: locationController.myLocation,
draggable: true,
icon: carIcon,
rotation: recentAngelToMarker,
// infoWindow: const InfoWindow(
// title: 'Time',
// ),
@@ -795,10 +882,10 @@ class MapDriverController extends GetxController {
passengerId = Get.arguments['passengerId'];
driverId = Get.arguments['driverId'];
distance = Get.arguments['Distance'];
name = Get.arguments['name'];
email = Get.arguments['email'];
passengerName = Get.arguments['name'];
passengerEmail = Get.arguments['email'];
totalPassenger = Get.arguments['totalPassenger'];
phone = Get.arguments['phone'];
passengerPhone = Get.arguments['phone'];
walletChecked = Get.arguments['WalletChecked'];
tokenPassenger = Get.arguments['tokenPassenger'];
direction = Get.arguments['direction'];

View File

@@ -12,8 +12,11 @@ import '../../functions/location_controller.dart';
class OrderRequestController extends GetxController {
double progress = 0;
int duration = 20;
double progressSpeed = 0;
int duration = 10;
int durationSpeed = 20;
int remainingTime = 0;
int remainingTimeSpeed = 0;
String countRefuse = '0';
bool applied = false;
final locationController = Get.put(LocationController());
@@ -81,19 +84,43 @@ class OrderRequestController extends GetxController {
if (applied == false) {
print('applied=========================');
print(applied);
refuseOrder(driverID, orderID);
refuseOrder(orderID);
}
}
}
void refuseOrder(String driverID, orderID) async {
void startTimerSpeed(String driverID, orderID) async {
for (int i = 0; i <= durationSpeed; i++) {
await Future.delayed(const Duration(seconds: 1));
progressSpeed = i / durationSpeed;
remainingTimeSpeed = durationSpeed - i;
update();
}
if (remainingTimeSpeed == 0) {
if (applied == false) {
print('applied=========================');
print(applied);
Get.back();
// refuseOrder(box.read(BoxName.driverID), orderID);
}
}
}
void refuseOrder(orderID) async {
await CRUD().postFromDialogue(link: AppLink.addDriverOrder, payload: {
//TODO need review
'driver_id': box.read(BoxName.driverID).toString(),
'driver_id': box.read(BoxName.driverID),
// box.read(BoxName.driverID).toString(),
'order_id': orderID,
'status': 'Refused'
});
await CRUD().post(link: AppLink.updateRides, payload: {
'id': orderID,
'rideTimeStart': DateTime.now().toString(),
'status': 'Refused',
'driver_id': box.read(BoxName.driverID),
});
Get.back();
// applied = true;
sql.insertData({

View File

@@ -64,7 +64,7 @@ GetBuilder<HomeCaptainController> callPage() {
Column(
children: [
Text(callController.status),
Text(Get.find<MapDriverController>().name.toString()),
Text(Get.find<MapDriverController>().passengerName.toString()),
],
),
GestureDetector(

View File

@@ -25,19 +25,19 @@ class ConnectWidget extends StatelessWidget {
builder: (homeCaptainController) => int.parse(
orderRequestController.countRefuse) >
3 ||
double.parse(captainWalletController.totalPoints) < -500
double.parse(captainWalletController.totalPoints) < -300
? CupertinoButton(
onPressed: () {
Get.defaultDialog(
// backgroundColor: CupertinoColors.destructiveRed,
barrierDismissible: false,
title: double.parse(captainWalletController.totalPoints) <
-500
-300
? 'You dont have Points'.tr
: 'You Are Stopped For this Day !'.tr,
titleStyle: AppStyle.title,
content: Text(
double.parse(captainWalletController.totalPoints) < -500
double.parse(captainWalletController.totalPoints) < -300
? 'You must be recharge your Account'.tr
: 'You Refused 3 Rides this Day that is the reason \nSee you Tomorrow!'
.tr,
@@ -45,7 +45,7 @@ class ConnectWidget extends StatelessWidget {
),
confirm:
double.parse(captainWalletController.totalPoints) <
-500
-300
? MyElevatedButton(
title: 'Recharge my Account'.tr,
onPressed: () {

View File

@@ -3,9 +3,11 @@ import 'package:flutter_font_icons/flutter_font_icons.dart';
import 'package:get/get.dart';
import 'package:SEFER/controller/home/captin/home_captain_controller.dart';
import 'package:SEFER/controller/home/captin/widget/zones_controller.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import '../../../../constant/colors.dart';
import '../../../../views/Rate/ride_calculate_driver.dart';
import '../../../functions/location_controller.dart';
GetBuilder<HomeCaptainController> leftMainMenuCaptainIcons() {
return GetBuilder<HomeCaptainController>(
@@ -78,6 +80,27 @@ GetBuilder<HomeCaptainController> leftMainMenuCaptainIcons() {
const SizedBox(
height: 5,
),
AnimatedContainer(
duration: const Duration(microseconds: 200),
width: controller.widthMapTypeAndTraffic,
decoration: BoxDecoration(
color: AppColor.secondaryColor,
border: Border.all(),
borderRadius: BorderRadius.circular(15)),
child: IconButton(
onPressed: () {
controller.mapHomeCaptaiController
.animateCamera(CameraUpdate.newLatLng(LatLng(
Get.find<LocationController>().myLocation.latitude,
Get.find<LocationController>().myLocation.longitude,
)));
},
icon: const Icon(
Icons.location_on,
size: 29,
),
),
),
AnimatedContainer(
duration: const Duration(microseconds: 200),
width: controller.widthMapTypeAndTraffic,

View File

@@ -3,6 +3,7 @@ import 'dart:convert';
import 'dart:math' show cos;
import 'dart:math' as math;
import 'package:SEFER/controller/functions/tts.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:geolocator/geolocator.dart';
@@ -20,8 +21,10 @@ import '../../constant/api_key.dart';
import '../../constant/box_name.dart';
import '../../constant/info.dart';
import '../../constant/links.dart';
import '../../constant/table_names.dart';
import '../../main.dart';
import '../../models/model/locations.dart';
import '../../views/home/map_widget.dart/car_details_widget_to_go.dart';
import '../../views/widgets/elevated_btn.dart';
import '../firebase/firbase_messge.dart';
import '../functions/crud.dart';
@@ -32,6 +35,7 @@ import '../payment/payment_controller.dart';
class MapPassengerController extends GetxController {
bool isLoading = true;
TextEditingController placeDestinationController = TextEditingController();
TextEditingController increasFeeFromPassenger = TextEditingController();
TextEditingController placeStartController = TextEditingController();
TextEditingController wayPoint0Controller = TextEditingController();
TextEditingController wayPoint1Controller = TextEditingController();
@@ -40,9 +44,14 @@ class MapPassengerController extends GetxController {
TextEditingController wayPoint4Controller = TextEditingController();
TextEditingController sosPhonePassengerProfile = TextEditingController();
final sosFormKey = GlobalKey<FormState>();
final increasFeeFormKey = GlobalKey<FormState>();
List data = [];
List<LatLng> bounds = [];
List placesStart = [];
List<String> driversToken = [];
LatLng previousLocationOfDrivers = LatLng(0, 0);
double angleDegrees = 0;
LatLng currentLocationOfDrivers = LatLng(0, 0);
List<TextEditingController> allTextEditingPlaces = [];
List placesDestination = [];
List wayPoint0 = [];
@@ -50,7 +59,7 @@ class MapPassengerController extends GetxController {
List wayPoint2 = [];
List wayPoint3 = [];
List wayPoint4 = [];
final textToSpeechController = Get.put(TextToSpeechController());
List<List<dynamic>> placeListResponseAll = [];
List<Widget> placeListResponse = [
@@ -123,7 +132,7 @@ class MapPassengerController extends GetxController {
bool isMainBottomMenuMap = true;
late Timer markerReloadingTimer2;
late Timer markerReloadingTimer1;
late int duration1;
late int durationToPassenger = 0;
bool isWayPointSheet = false;
bool isWayPointStopsSheet = false;
bool isWayPointStopsSheetUtilGetMap = false;
@@ -145,7 +154,7 @@ class MapPassengerController extends GetxController {
double progress = 0;
double progressTimerToPassengerFromDriverAfterApplied = 0;
double progressTimerDriverWaitPassenger5Minute = 0;
int durationTimer = 25;
int durationTimer = 9;
int durationToRide = 0;
int remainingTime = 25;
int remainingTimeToPassengerFromDriverAfterApplied = 60;
@@ -181,6 +190,7 @@ class MapPassengerController extends GetxController {
bool noCarString = false;
bool isCashSelectedBeforeConfirmRide = false;
bool isPassengerChosen = false;
bool isSearchingWindow = false;
bool currentLocationToFormPlaces = false;
bool currentLocationToFormPlaces0 = false;
bool currentLocationToFormPlaces1 = false;
@@ -196,6 +206,9 @@ class MapPassengerController extends GetxController {
late double tax = 0;
late double totalPassenger = 0;
late double totalCostPassenger = 0;
late double totalPassengerComfort = 0;
late double totalPassengerComfortDiscount = 0;
late double totalPassengerMotoDelivery = 0;
late double totalDriver = 0;
late double averageDuration = 0;
late double costDuration = 0;
@@ -306,6 +319,22 @@ class MapPassengerController extends GetxController {
}
}
increaseFeeByPassengerAndReOrder() async {
if (increasFeeFormKey.currentState!.validate()) {
if (double.parse(increasFeeFromPassenger.text) > totalPassenger) {
totalPassenger = double.parse(increasFeeFromPassenger.text);
Get.back();
if (rideId != 'yet') {
await CRUD().post(link: AppLink.updateDriverOrder, payload: {
"order_id": rideId.toString(), // Convert to String
"status": 'Cancel'
});
}
confirmRideForFirstDriver();
}
}
}
void convertHintTextPlaces1(int index) {
if (wayPoint1.isEmpty) {
hintTextwayPoint1 = 'Search for your Start point'.tr;
@@ -397,6 +426,9 @@ class MapPassengerController extends GetxController {
isCashConfirmPageShown = !isCashConfirmPageShown;
isCashSelectedBeforeConfirmRide = true;
cashConfirmPageShown = isCashConfirmPageShown == true ? 250 : 0;
// to get or sure picker point for origin //todo
// isPickerShown = true;
// clickPointPosition();
update();
}
@@ -459,8 +491,22 @@ class MapPassengerController extends GetxController {
update();
}
calcualateDistsanceInMetet(LatLng prev, current) async {
double distance2 = Geolocator.distanceBetween(
prev.latitude,
prev.longitude,
current.latitude,
current.longitude,
);
return distance2;
}
bool isTimerFromDriverToPassengerAfterAppliedRunning = true;
void startTimerFromDriverToPassengerAfterApplied() async {
for (int i = 0; i <= timeToPassengerFromDriverAfterApplied; i++) {
for (int i = 0;
i <= timeToPassengerFromDriverAfterApplied &&
isTimerFromDriverToPassengerAfterAppliedRunning;
i++) {
await Future.delayed(const Duration(seconds: 1));
progressTimerToPassengerFromDriverAfterApplied =
i / timeToPassengerFromDriverAfterApplied;
@@ -483,7 +529,14 @@ class MapPassengerController extends GetxController {
}
}
// Function to stop the timer
void stopTimerFromDriverToPassengerAfterApplied() {
isTimerFromDriverToPassengerAfterAppliedRunning = false;
update();
}
void startTimerDriverWaitPassenger5Minute() async {
stopTimerFromDriverToPassengerAfterApplied();
isDriverArrivePassenger = true;
isDriverInPassengerWay = false;
timeToPassengerFromDriverAfterApplied = 0;
@@ -572,7 +625,7 @@ class MapPassengerController extends GetxController {
var res = await CRUD()
.get(link: AppLink.getRideStatusBegin, payload: {'ride_id': rideId});
if (res == 'failure') {
//print(res);
// print(res);
}
var decode = jsonDecode(res);
@@ -685,13 +738,17 @@ class MapPassengerController extends GetxController {
update();
}
int currentTimeSearchingCaptainWindow = 0;
late String driverPhone;
late String driverRate;
late String firstName;
late String carColor;
late String carYear;
late String model;
late String licensePlate;
changeConfirmRide() async {
confirmRideForFirstDriver() async {
await getCarsLocationByPassenger();
await getNearestDriverByPassengerLocation();
await getNearestDriverByPassengerLocationAPIGOOGLE();
if (dataCarsLocationByPassenger != 'failure') {
driverToken =
@@ -701,10 +758,17 @@ class MapPassengerController extends GetxController {
firstName = dataCarsLocationByPassenger['message'][carsOrder]
['first_name']
.toString();
carColor =
dataCarsLocationByPassenger['message'][carsOrder]['color'].toString();
driverRate = dataCarsLocationByPassenger['message'][carsOrder]
['ratingDriver']
.toString();
carYear =
dataCarsLocationByPassenger['message'][carsOrder]['year'].toString();
model =
dataCarsLocationByPassenger['message'][carsOrder]['model'].toString();
'${dataCarsLocationByPassenger['message'][carsOrder]['model']} - ${dataCarsLocationByPassenger['message'][carsOrder]['make']}';
licensePlate = dataCarsLocationByPassenger['message'][carsOrder]
['license_plate']
['car_plate']
.toString();
PaymentController paymentController = Get.find<PaymentController>();
@@ -712,6 +776,7 @@ class MapPassengerController extends GetxController {
shouldFetch = true;
isBottomSheetShown = false;
timeToPassengerFromDriverAfterApplied = 60;
isDriversTokensSend = false;
update();
// //print('rideConfirm= $rideConfirm');
@@ -754,7 +819,7 @@ class MapPassengerController extends GetxController {
distanceByPassenger.toString(),
paymentController.isWalletChecked.toString(),
dataCarsLocationByPassenger['message'][carsOrder]['token'].toString(),
duration1.toString(),
durationToPassenger.toString(),
rideId,
rideTimerBegin.toString(),
dataCarsLocationByPassenger['message'][carsOrder]['driver_id']
@@ -775,12 +840,13 @@ class MapPassengerController extends GetxController {
: '0',
box.read(BoxName.email).toString(),
];
FirebaseMessagesController().sendNotificationToDriverMAP(
'Order',
jsonDecode(value)['message'].toString(),
dataCarsLocationByPassenger['message'][carsOrder]['token'].toString(),
body,
);
FirebaseMessagesController().sendNotificationToDriverMapPolyline(
'Order',
jsonDecode(value)['message'].toString(),
dataCarsLocationByPassenger['message'][carsOrder]['token']
.toString(),
body,
polylineCoordinates.toString());
// //print(dataCarsLocationByPassenger);
// //print(dataCarsLocationByPassenger['message'][0]['token'].toString());
});
@@ -801,42 +867,130 @@ class MapPassengerController extends GetxController {
}
}
bool isDriversTokensSend = false;
confirmRideForAllDriverAvailable() async {
// isDriversTokensSend = true;
PaymentController paymentController = Get.find<PaymentController>();
rideConfirm = true;
shouldFetch = true;
isBottomSheetShown = false;
timeToPassengerFromDriverAfterApplied = 60;
List<String> body = [
'${data[0]["start_location"]['lat']},${data[0]["start_location"]['lng']}',
'${data[0]["end_location"]['lat']},${data[0]["end_location"]['lng']}',
totalPassenger.toStringAsFixed(2),
totalDriver.toStringAsFixed(2),
durationToRide.toString(),
distance.toStringAsFixed(2),
dataCarsLocationByPassenger['message'][carsOrder]['driver_id'].toString(),
box.read(BoxName.passengerID).toString(),
box.read(BoxName.name).toString(),
box.read(BoxName.tokenFCM).toString(),
box.read(BoxName.phone).toString(),
durationByPassenger.toString(),
distanceByPassenger.toString(),
paymentController.isWalletChecked.toString(),
dataCarsLocationByPassenger['message'][carsOrder]['token'].toString(),
durationToPassenger.toString(),
rideId,
rideTimerBegin.toString(),
dataCarsLocationByPassenger['message'][carsOrder]['driver_id'].toString(),
durationToRide.toString(),
Get.find<WayPointController>().wayPoints.length > 1
? 'haveSteps'
: 'startEnd',
placesCoordinate[0],
placesCoordinate[1],
placesCoordinate[2],
placesCoordinate[3],
placesCoordinate[4],
costDistance.toStringAsFixed(2),
double.parse(box.read(BoxName.passengerWalletTotal)) < 0
? double.parse(box.read(BoxName.passengerWalletTotal))
.toStringAsFixed(2)
: '0',
box.read(BoxName.email).toString(),
];
print('driversToken');
print(driversToken);
for (var i = 0; i < driversToken.length; i++) {
FirebaseMessagesController().sendNotificationToDriverMapPolyline(
'OrderSpeed',
rideId.toString(),
driversToken[i],
body,
polylineCoordinates.toString());
}
delayAndFetchRideStatus(rideId);
// if (shouldFetch == false) {
// startTimer();
// update();
// }
update();
// } else {
// Get.defaultDialog(
// title: 'No Car or Driver Found in your area.'.tr,
// titleStyle: AppStyle.title,
// middleText: 'Please Try anther time '.tr,
// middleTextStyle: AppStyle.title.copyWith(color: AppColor.yellowColor),
// confirm:
// MyElevatedButton(title: 'Ok'.tr, onPressed: () => Get.back()));
// }
}
String statusRide = 'wait';
void delayAndFetchRideStatus(String rideId) {
Timer(const Duration(milliseconds: 200), () async {
if (shouldFetch) {
// //print('shouldFetch is =$shouldFetch');
var res = await CRUD()
.get(link: AppLink.getRideStatus, payload: {'order_id': rideId});
.get(link: AppLink.getRideStatus, payload: {'id': rideId});
print(res);
var decod = jsonDecode(res);
//print(' 0000000000000000000000000000000000000000000000000');
//print(decod['data']);
print(' 0000000000000000000000000000000000000000000000000');
print(decod['data']);
if (decod['data'].toString() == 'Apply') {
getUpdatedRideForDriverApply(rideId);
shouldFetch = false; // Stop further fetches
statusRide = 'Apply';
rideConfirm = false;
isSearchingWindow = false;
update();
startTimer();
} else if (decod['data'].toString() == 'Refused') {
carsOrder = carsOrder + 1;
update();
//print(dataCarsLocationByPassenger['message'].length);
//print(dataCarsLocationByPassenger['message']);
//print(carsOrder);
if (carsOrder < dataCarsLocationByPassenger['message'].length) {
//print('55555555555555555555');
changeConfirmRide();
} else {
Get.defaultDialog(
barrierDismissible: false,
title: 'There no Driver Aplly your order sorry for that '.tr,
middleText: 'try next time .',
confirm: MyElevatedButton(
title: 'Back',
onPressed: () => Get.offAll(const MapPagePassenger()),
));
cancelRideAfterRejectFromAll();
// isDriversTokensSend = false;
if (isDriversTokensSend == false) {
confirmRideForAllDriverAvailable();
isDriversTokensSend = true;
}
// else{
// j
// }
// else {
// Get.defaultDialog(
// barrierDismissible: false,
// title: 'There no Driver Aplly your order sorry for that '.tr,
// // middleText: 'try next time .'.tr,
// content: IconButton(
// onPressed: () {
// textToSpeechController.speakText(
// 'There no Driver Aplly your order sorry for that '.tr);
// },
// icon: const Icon(
// Icons.headphones,
// size: 40,
// ),
// ),
// titleStyle: AppStyle.title,
// confirm: MyElevatedButton(
// title: 'Back',
// onPressed: () => Get.offAll(const MapPagePassenger()),
// ));
// cancelRideAfterRejectFromAll();
// }
} else {
delayAndFetchRideStatus(
rideId); // Repeat the delay and fetch operation
@@ -855,7 +1009,7 @@ class MapPassengerController extends GetxController {
rideConfirm = false;
// //print(timeToPassengerFromDriverAfterApplied);
timeToPassengerFromDriverAfterApplied += duration1;
timeToPassengerFromDriverAfterApplied += durationToPassenger;
// //print(duration1);
// //print('timeToPassengerFromDriverAfterApplied====' +
@@ -883,15 +1037,36 @@ class MapPassengerController extends GetxController {
return response['status'];
}
late String driverCarModel, driverCarMake, driverLicensePlate, driverName;
getUpdatedRideForDriverApply(String rideId) async {
// if (isDriversTokensSend) {
final response =
await CRUD().get(link: AppLink.getRideOrderID, payload: {'id': rideId});
if (response != 'failure') {
driverId = response['data']['driver_id'];
driverPhone = response['data']['phone'];
driverCarMake = response['data']['make'];
driverCarModel = response['data']['model'];
driverLicensePlate = response['data']['license_plate'];
driverName = response['data']['first_name'];
driverToken = response['data']['token'];
}
driversToken.remove(driverToken);
for (var i = 0; i < driversToken.length; i++) {
FirebaseMessagesController().sendNotificationToAnyWithoutData(
'Order Applied',
'$driverName Apply order\nTake attention in other order'.tr,
driversToken[i]);
}
// }
}
late LatLng currentDriverLocation;
Future getCarsLocationByPassenger() async {
// if (rideConfirm == false) {
carsLocationByPassenger = [];
LatLngBounds bounds = calculateBounds(
passengerLocation.latitude, passengerLocation.longitude, 4000);
//print(
// 'Southwest: ${bounds.southwest.latitude}, ${bounds.southwest.longitude}');
//print(
// 'Northeast: ${bounds.northeast.latitude}, ${bounds.northeast.longitude}');
passengerLocation.latitude, passengerLocation.longitude, 7000);
var res =
await CRUD().get(link: AppLink.getCarsLocationByPassenger, payload: {
@@ -916,20 +1091,36 @@ class MapPassengerController extends GetxController {
// }
// //print('driverId==============$driverId');
carsLocationByPassenger.clear(); // Clear existing markers
late LatLng lastDriverLocation; // Initialize a variable for last location
for (var i = 0; i < dataCarsLocationByPassenger['message'].length; i++) {
carsLocationByPassenger.add(LatLng(
double.parse(dataCarsLocationByPassenger['message'][i]['latitude']),
double.parse(
dataCarsLocationByPassenger['message'][i]['longitude'])));
update();
currentDriverLocation = LatLng(
double.parse(dataCarsLocationByPassenger['message'][i]['latitude']),
double.parse(dataCarsLocationByPassenger['message'][i]['longitude']),
);
// Update lastDriverLocation on each iteration
previousLocationOfDrivers = currentDriverLocation;
carsLocationByPassenger.add(currentDriverLocation);
driversToken.add(dataCarsLocationByPassenger['message'][i]['token']);
}
update();
// // Calculate rotation angle here (explained below)
// if (previousLocationOfDrivers != null) {
// angleDegrees = calculateAngleBetweenLocations(
// previousLocationOfDrivers, currentDriverLocation);
// // Use rotationAngle for marker rotation logic
// }
update();
}
}
late LatLng driverLocationToPassenger = LatLng(32, 35);
LatLng driverLocationToPassenger = LatLng(32, 35);
Future getDriverCarsLocationToPassengerAfterApplied() async {
driverCarsLocationToPassengerAfterApplied = [];
@@ -954,7 +1145,7 @@ class MapPassengerController extends GetxController {
Future runEvery30SecondsUntilConditionMet() async {
// Calculate the duration of the trip in minutes.
double tripDurationInMinutes = duration1 / 4;
double tripDurationInMinutes = durationToPassenger / 4;
int loopCount = tripDurationInMinutes.ceil();
// If the trip duration is less than or equal to 50 minutes, then break the loop.
for (var i = 0; i < loopCount; i++) {
@@ -972,7 +1163,13 @@ class MapPassengerController extends GetxController {
for (var i = 0; i < driverCarsLocationToPassengerAfterApplied.length; i++) {
// }
// for (var item in driverCarsLocationToPassengerAfterApplied) {
final marker = Marker(
double rotationCar = calculateAngleBetweenLocations(
LatLng(driverCarsLocationToPassengerAfterApplied[i - 1].latitude,
driverCarsLocationToPassengerAfterApplied[i - 1].longitude),
LatLng(driverCarsLocationToPassengerAfterApplied[i].latitude,
driverCarsLocationToPassengerAfterApplied[i].longitude));
final driverAcceptedMarker = Marker(
onTap: () => print('marker pressed'),
infoWindow: InfoWindow(
title:
'${driverCarsLocationToPassengerAfterApplied[i].latitude} minutes'),
@@ -981,8 +1178,9 @@ class MapPassengerController extends GetxController {
.toString()),
position: LatLng(driverCarsLocationToPassengerAfterApplied[i].latitude,
driverCarsLocationToPassengerAfterApplied[i].longitude),
rotation: rotationCar,
);
markers.add(marker);
markers.add(driverAcceptedMarker);
update();
mapController?.animateCamera(CameraUpdate.newLatLng(LatLng(
driverCarsLocationToPassengerAfterApplied[i].latitude,
@@ -1042,6 +1240,7 @@ class MapPassengerController extends GetxController {
rideConfirm = false;
shouldFetch = false;
isCashConfirmPageShown = false;
isSearchingWindow = false;
isPassengerChosen = false;
isCashSelectedBeforeConfirmRide = false;
isPickerShown = false;
@@ -1068,6 +1267,7 @@ class MapPassengerController extends GetxController {
rideConfirm = false;
shouldFetch = false;
isCashConfirmPageShown = false;
isSearchingWindow = false;
isPassengerChosen = false;
isCashSelectedBeforeConfirmRide = false;
haveSteps = false;
@@ -1104,7 +1304,7 @@ class MapPassengerController extends GetxController {
} else {
isMainBottomMenuMap = !isMainBottomMenuMap;
mainBottomMenuMapHeight =
isMainBottomMenuMap == true ? Get.height * .2 : Get.height * .6;
isMainBottomMenuMap == true ? Get.height * .2 : Get.height * .45;
isWayPointSheet = false;
if (heightMenuBool == true) {
getDrawerMenu();
@@ -1423,47 +1623,58 @@ class MapPassengerController extends GetxController {
// });
// }
void startMarkerReloading() {
Future startMarkerReloading() async {
int reloadCount = 0;
Timer.periodic(const Duration(seconds: 12), (timer) {
Timer.periodic(const Duration(seconds: 3), (timer) {
reloadCount++;
//print('Reloading markers ($reloadCount)');
reloadMarkers();
if (reloadCount >= 6) {
if (reloadCount >= 70) {
timer.cancel(); // Stop the timer after 5 reloads
//print('Marker reloading completed.');
}
});
}
void reloadMarkers() async {
await getCarsLocationByPassenger();
reloadMarkers() async {
if (statusRide == 'wait') {
await getCarsLocationByPassenger();
await getNearestDriverByPassengerLocation();
// markers.clear();
// Clear existing markers
// mapController!.showMarkerInfoWindow(MarkerId('g'));
markers.clear();
update();
// if (rideConfirm) {
getNearestDriverByPassengerLocation();
// }
// Add new markers
// Example: Add a marker for each item in a list
for (var item in carsLocationByPassenger) {
final marker = Marker(
infoWindow: InfoWindow(title: '${item.latitude} minutes'),
markerId: MarkerId(duration1.toString()),
position: LatLng(item.latitude, item.longitude),
// Other properties for the marker, such as icon, info window, etc.
);
markers.add(marker);
// update();
// if (rideConfirm) {
// }
// Add new markers
// Example: Add a marker for each item in a list
for (var item in carsLocationByPassenger) {
// if (previousLocationOfDrivers != null) {
// angleDegrees = calculateAngleBetweenLocations(
// previousLocationOfDrivers, currentLocationOfDrivers);
// // Use the calculated angle for rotation, if needed
// print('angleDegrees $angleDegrees');
// print('previousLocationOfDrivers $previousLocationOfDrivers');
// print('currentLocationOfDrivers $currentLocationOfDrivers');
// }
final marker = Marker(
infoWindow: InfoWindow(title: '${item.latitude} minutes'),
markerId: MarkerId(durationToPassenger.toString()),
position: LatLng(item.latitude, item.longitude),
rotation: math.Random().nextDouble() * 360,
// Other properties for the marker, such as icon, info window, etc.
);
markers.add(marker);
update();
}
// Update the map with the new markers
// mapController?.animateCamera(CameraUpdate.newLatLng(
// LatLng(passengerLocation.latitude, passengerLocation.longitude)));
}
// Update the map with the new markers
// mapController?.animateCamera(CameraUpdate.newLatLng(
// LatLng(passengerLocation.latitude, passengerLocation.longitude)));
}
String durationByPassenger = '';
@@ -1471,8 +1682,57 @@ class MapPassengerController extends GetxController {
late DateTime timeFromDriverToPassenger = DateTime.now();
String distanceByPassenger = '';
late Duration durationFromDriverToPassenger;
double nearestDistance = double.infinity;
Future<CarLocation?> getNearestDriverByPassengerLocation() async {
if (polyLines.isEmpty || data.isEmpty) {
return null; // Early return if data is empty
}
if (!rideConfirm) {
if (dataCarsLocationByPassenger != 'failure') {
if (dataCarsLocationByPassenger['message'].length > 0) {
for (var i = 0;
i < dataCarsLocationByPassenger['message'].length;
i++) {
var carLocation = dataCarsLocationByPassenger['message'][i];
durationToPassenger = 100; //////
// Calculate the distance between the passenger's location and the current driver's location
final distance = Geolocator.distanceBetween(
passengerLocation.latitude,
passengerLocation.longitude,
double.parse(carLocation['latitude']),
double.parse(carLocation['longitude']),
);
getNearestDriverByPassengerLocation() async {
// Update the UI with the distance and duration
update();
// If the distance is less than the nearest distance, update the nearest driver
if (distance < nearestDistance) {
nearestDistance = distance;
nearestCar = CarLocation(
distance: distance,
duration:
0, // We don't have duration information from Geolocator
id: carLocation['driver_id'],
latitude: double.parse(carLocation['latitude']),
longitude: double.parse(carLocation['longitude']),
);
print('nearestCar ${nearestDistance.toStringAsFixed(0)}');
// Update the UI with the nearest driver
update();
}
}
}
}
}
// Return the nearest driver
return nearestCar;
}
getNearestDriverByPassengerLocationAPIGOOGLE() async {
if (polyLines.isEmpty || data.isEmpty) {
return null; // Early return if data is empty
}
@@ -1499,10 +1759,11 @@ class MapPassengerController extends GetxController {
data['rows'][0]['elements'][0]['distance']['value'];
distanceByPassenger =
data['rows'][0]['elements'][0]['distance']['text'];
duration1 = data['rows'][0]['elements'][0]['duration']['value'];
durationToPassenger =
data['rows'][0]['elements'][0]['duration']['value'];
durationFromDriverToPassenger =
Duration(seconds: duration1.toInt());
Duration(seconds: durationToPassenger.toInt());
newTime1 = currentTime.add(durationFromDriverToPassenger);
timeFromDriverToPassenger =
newTime1.add(Duration(minutes: 2.toInt()));
@@ -1514,7 +1775,7 @@ class MapPassengerController extends GetxController {
nearestCar = CarLocation(
distance: distance1.toDouble(),
duration: duration1.toDouble(),
duration: durationToPassenger.toDouble(),
id: carLocation['driver_id'],
latitude: double.parse(carLocation['latitude']),
longitude: double.parse(carLocation['longitude']),
@@ -1541,7 +1802,7 @@ class MapPassengerController extends GetxController {
//print(nearestCar!.id);
}
calculateDistanceBetweenPassengerAndDriverBeforecancelRide() async {
calculateDistanceBetweenPassengerAndDriverBeforeCancelRide() async {
await getDriverCarsLocationToPassengerAfterApplied();
double distance = Geolocator.distanceBetween(
passengerLocation.latitude,
@@ -1569,6 +1830,23 @@ class MapPassengerController extends GetxController {
}
List<double> headingAngles = [];
double calculateAngleBetweenLocations(LatLng start, LatLng end) {
double startLat = start.latitude * math.pi / 180;
double startLon = start.longitude * math.pi / 180;
double endLat = end.latitude * math.pi / 180;
double endLon = end.longitude * math.pi / 180;
double dLon = endLon - startLon;
double y = math.sin(dLon) * cos(endLat);
double x = cos(startLat) * math.sin(endLat) -
math.sin(startLat) * cos(endLat) * cos(dLon);
double angle = math.atan2(y, x);
double angleDegrees = angle * 180 / math.pi;
return angleDegrees;
}
late LatLngBounds boundsData;
getMap(String origin, destination) async {
@@ -1579,9 +1857,10 @@ class MapPassengerController extends GetxController {
double latPassengerDestination = double.parse(coordDestination[0]);
double lngPassengerDestination = double.parse(coordDestination[1]);
myDestination = LatLng(latPassengerDestination, lngPassengerDestination);
// if (origin.isEmpty) {
// origin = passengerLocation.toString(); //todo
// }
if (origin.isEmpty) {
origin =
'${passengerLocation.latitude.toString().split(',')[0]},${passengerLocation.longitude.toString().split(',')[1]}'; //todo
}
isLoading = false;
update();
var url =
@@ -1622,23 +1901,7 @@ class MapPassengerController extends GetxController {
double distanceOfTrip = (data[0]['distance']['value']) / 1000;
distance = distanceOfTrip;
// updateCameraForDistanceAfterGetMap();
for (var step in data[0]['steps']) {
var startLat = step['start_location']['lat'];
var startLng = step['start_location']['lng'];
var endLat = step['end_location']['lat'];
var endLng = step['end_location']['lng'];
// Calculate heading
var y = math.sin(endLng - startLng) * math.cos(endLat);
var x = math.cos(startLat) * math.sin(endLat) -
math.sin(startLat) * math.cos(endLat) * math.cos(endLng - startLng);
var theta = math.atan2(y, x);
// Add to list
headingAngles.add(theta);
}
print(headingAngles);
if (polyLines.isNotEmpty) {
clearPolyline();
} else {
@@ -1799,6 +2062,15 @@ class MapPassengerController extends GetxController {
update();
}
int selectedIndex = -1; // Initialize with no selection
void selectCarFromList(int index) {
selectedIndex = index; // Update selected index
carTypes.forEach(
(element) => element.isSelected = false); // Reset selection flags
carTypes[index].isSelected = true;
update();
}
showBottomSheet1() async {
bottomSheet();
isBottomSheetShown = true;
@@ -1834,9 +2106,11 @@ class MapPassengerController extends GetxController {
if (double.parse(box.read(BoxName.passengerWalletTotal)) < 0) {
totalPassenger = totalCostPassenger -
(totalCostPassenger * int.parse(firstElement['amount']) / 100);
update();
} else {
totalPassenger = totalCostPassenger -
(totalCostPassenger * int.parse(firstElement['amount']) / 100);
update();
}
totalDriver = totalDriver -
@@ -1874,46 +2148,57 @@ class MapPassengerController extends GetxController {
print('costDistance----- $costDistance');
print(
'passengerWalletTotal----- ${box.read(BoxName.passengerWalletTotal)}');
update();
if (currentTime.hour >= 22) {
costDistance = distance * 3.7;
update();
} else if (currentTime.hour < 5) {
costDistance = distance * 3.8;
update();
} else if (currentTime.hour >= 13 && currentTime.hour <= 16) {
if (averageDuration > 2.5) {
costDistance = distance * 3.9;
update();
} else {
costDistance = distance * 3.5;
update();
}
} else {
costDistance = distance * 3.4;
update();
}
//print('cost $cost');
// if (double.parse(box.read(BoxName.passengerWalletTotal)) < 0) {
// totalPassenger = totalCostPassenger +
// (-1) * (double.parse(box.read(BoxName.passengerWalletTotal)));
// update();
// } else {
// totalPassenger = totalCostPassenger;
// update();
// }
var totalDriver1 = costDistance + costDuration;
totalCostPassenger = totalDriver1 + (totalDriver1 * .16);
totalPassenger = totalCostPassenger;
totalPassengerComfort = totalCostPassenger + (totalCostPassenger * .2);
totalPassengerComfortDiscount =
totalPassengerComfort + totalPassengerComfort * 12 / 100;
totalPassengerMotoDelivery =
totalCostPassenger - (totalCostPassenger * .35);
totalDriver = totalDriver1 + (totalDriver1 * .16);
tax = totalCostPassenger * .16;
totalME = totalCostPassenger - tax;
if (double.parse(box.read(BoxName.passengerWalletTotal)) < 0) {
totalPassenger = totalCostPassenger +
(-1) * (double.parse(box.read(BoxName.passengerWalletTotal)));
} else {
totalPassenger = totalCostPassenger;
}
update();
if (currentTime.hour >= 22) {
costDistance = distance * 0.23;
update();
} else if (currentTime.hour < 5) {
costDistance = distance * 0.25;
update();
} else if (currentTime.hour >= 13 && currentTime.hour <= 16) {
if (averageDuration > 2.5) {
costDistance = distance * 0.25;
update();
} else {
costDistance = distance * 0.21;
update();
}
} else {
costDistance = distance * 0.21;
update();
}
//print('cost $cost');
if (totalCostPassenger < 1) {
totalCostPassenger = 1;
if (double.parse(box.read(BoxName.passengerWalletTotal)) < 0) {
totalPassenger = totalCostPassenger +
(-1) * (double.parse(box.read(BoxName.passengerWalletTotal)));
update();
} else {
totalPassenger = totalCostPassenger;
update();
}
update();
@@ -2011,20 +2296,27 @@ class MapPassengerController extends GetxController {
}
}
late List recentPlaces = [];
getFavioratePlaces() async {
recentPlaces = await sql.getAllData(TableName.recentLocations);
}
@override
void onInit() async {
mapAPIKEY = await storage.read(key: BoxName.mapAPIKEY);
getFavioratePlaces();
readyWayPoints();
await getLocation();
await addToken();
await getCarsLocationByPassenger();
getNearestDriverByPassengerLocation();
await startMarkerReloading();
// await getCarsLocationByPassenger();
// await getNearestDriverByPassengerLocation();
addCustomPicker();
addCustomCarIcon();
addCustomStepIcon();
addCustomStartIcon();
addCustomEndIcon();
startMarkerReloading();
initilizeGetStorage();
cardNumber = await SecureStorage().readData(BoxName.cardNumber);