This commit is contained in:
Hamza-Ayed
2024-01-01 00:56:25 +03:00
parent 8475bdc831
commit e3a63e18fc
13 changed files with 437 additions and 292 deletions

View File

@@ -1,38 +1,28 @@
import 'dart:convert';
import 'package:flutter/animation.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:get/get.dart';
import 'package:ride/constant/box_name.dart';
import 'package:ride/constant/links.dart';
import 'package:ride/controller/functions/crud.dart';
import 'package:ride/main.dart';
import 'package:ride/models/model/driver/rides_summary_model.dart';
class DurationController extends GetxController
with GetSingleTickerProviderStateMixin {
final data = <DurationData>[].obs;
late AnimationController animationController;
@override
void onInit() {
super.onInit();
fetchData();
animationController = AnimationController(
vsync: this,
duration: const Duration(
milliseconds: 500), // Adjust the animation duration as needed
);
animationController.forward(); // Start the animation
}
@override
void onClose() {
animationController.dispose();
super.onClose();
}
Map<String, dynamic> jsonData = {};
class DurationController extends GetxController {
final data = DurationData;
// late AnimationController animationController;
late List<MonthlyDataModel> rideData;
Map<String, dynamic> jsonData1 = {};
bool isLoading = false;
String totalDurationToday = '';
var chartData;
@override
void onInit() async {
super.onInit();
await fetchData();
}
Future<void> fetchData() async {
isLoading = true;
update(); // Notify the observers about the loading state change
@@ -41,13 +31,22 @@ class DurationController extends GetxController
link: AppLink.getTotalDriverDuration,
payload: {'driver_id': box.read(BoxName.driverID)},
);
jsonData = jsonDecode(res);
final parsedData = parseData(jsonData['message']);
data.value = parsedData;
jsonData1 = jsonDecode(res);
var jsonResponse = jsonDecode(res) as Map<String, dynamic>;
isLoading = false;
// print(jsonResponse);
final List<dynamic> jsonData = jsonResponse['message'];
rideData = jsonData.map<MonthlyDataModel>((item) {
return MonthlyDataModel.fromJson(item);
}).toList();
final List<FlSpot> spots = rideData
.map((data) => FlSpot(
data.day.toDouble(),
data.totalDuration.toDouble(),
))
.toList();
chartData = spots;
update(); // Notify the observers about the data and loading state change
}

View File

@@ -21,12 +21,16 @@ import '../../functions/location_controller.dart';
class MapDriverController extends GetxController {
bool isLoading = true;
List data = [];
List dataDestination = [];
LatLngBounds? boundsData;
BitmapDescriptor carIcon = BitmapDescriptor.defaultMarker;
final List<LatLng> polylineCoordinates = [];
final List<LatLng> polylineCoordinatesDestination = [];
List<Polyline> polyLines = [];
List<Polyline> polyLinesDestination = [];
Set<Marker> markers = {};
late String passengerLocation;
late String passengerDestination;
late String duration;
late String distance;
late String name;
@@ -46,7 +50,7 @@ class MapDriverController extends GetxController {
bool isBtnRideBegin = false;
bool isRideFinished = false;
bool isRideStarted = false;
double passengerInfoWindow = Get.height * .32;
double passengerInfoWindow = Get.height * .35;
double progress = 0;
double progressToPassenger = 0;
bool isRideBegin = false;
@@ -69,12 +73,12 @@ class MapDriverController extends GetxController {
mapController = controller;
controller.getVisibleRegion();
controller.animateCamera(
CameraUpdate.newLatLngZoom(myLocation, 15),
CameraUpdate.newLatLngZoom(myLocation, 17),
);
update();
// Set up a timer or interval to trigger the marker update every 3 seconds.
timer = Timer.periodic(const Duration(seconds: 3), (_) {
timer = Timer.periodic(const Duration(seconds: 2), (_) {
updateMarker();
});
}
@@ -111,7 +115,9 @@ class MapDriverController extends GetxController {
void clearPolyline() {
polyLines = [];
polyLinesDestination = [];
polylineCoordinates.clear();
polylineCoordinatesDestination.clear();
update();
}
@@ -371,6 +377,45 @@ class MapDriverController extends GetxController {
}
}
getMapDestination(String origin, destination) async {
var url =
('${AppLink.googleMapsLink}directions/json?&language=en&avoid=tolls|ferries&destination=$destination&origin=$origin&key=${AK.mapAPIKEY}');
var response = await CRUD().getGoogleApi(link: url, payload: {});
dataDestination = response['routes'][0]['legs'];
// print(data);
final points =
decodePolyline(response["routes"][0]["overview_polyline"]["points"]);
for (int i = 0; i < points.length; i++) {
double lat = points[i][0].toDouble();
double lng = points[i][1].toDouble();
polylineCoordinatesDestination.add(LatLng(lat, lng));
}
if (polyLinesDestination.isNotEmpty) {
clearPolyline();
var polyline = Polyline(
polylineId: PolylineId(response["routes"][0]["summary"]),
points: polylineCoordinatesDestination,
width: 10,
color: AppColor.redColor,
);
polyLinesDestination.add(polyline);
// rideConfirm = false;
update();
} else {
var polyline = Polyline(
polylineId: PolylineId(response["routes"][0]["summary"]),
points: polylineCoordinatesDestination,
width: 10,
color: AppColor.redColor,
);
polyLinesDestination.add(polyline);
// rideConfirm = false;
update();
}
}
void changePassengerInfoWindow() {
isPassengerInfoWindow = !isPassengerInfoWindow;
passengerInfoWindow = isPassengerInfoWindow == true ? 200 : 0;
@@ -382,6 +427,7 @@ class MapDriverController extends GetxController {
mapAPIKEY = await storage.read(key: BoxName.mapAPIKEY);
// Get the passenger location from the arguments.
passengerLocation = Get.arguments['passengerLocation'];
passengerDestination = Get.arguments['passengerDestination'];
duration = Get.arguments['Duration'];
passengerId = Get.arguments['passengerId'];
driverId = Get.arguments['driverId'];
@@ -401,6 +447,7 @@ class MapDriverController extends GetxController {
String origin = '$lat,$lng';
// Set the origin and destination coordinates for the Google Maps directions request.
getMap(origin, passengerLocation);
await getMapDestination(passengerLocation, passengerDestination);
addCustomCarIcon();
// updateMarker();
startTimerToShowPassengerInfoWindowFromDriver();

View File

@@ -87,7 +87,7 @@ GetBuilder<HomeCaptainController> leftMainMenuCaptainIcons() {
borderRadius: BorderRadius.circular(15)),
child: IconButton(
onPressed: () {
Get.to(() => const RideCalculateDriver());
Get.to(() => RideCalculateDriver());
},
icon: const Icon(FontAwesome5.chart_bar),
),

View File

@@ -366,7 +366,7 @@ class MapPassengerController extends GetxController {
['driver_id']
.toString(),
"status": "waiting",
"price_for_driver": totalDriver.toString(),
"price_for_driver": totalPassenger.toString(),
"price_for_passenger": totalME.toString(),
"distance": distance.toString()
}).then((value) {
@@ -934,69 +934,72 @@ class MapPassengerController extends GetxController {
if (polyLines.isEmpty || data.isEmpty) {
if (rideConfirm == false) {
double nearestDistance = double.infinity;
for (var i = 0;
i < dataCarsLocationByPassenger['message'].length;
i++) {
var carLocation = dataCarsLocationByPassenger['message'][i];
if (dataCarsLocationByPassenger['message'].length > 0) {
for (var i = 0;
i < dataCarsLocationByPassenger['message'].length;
i++) {
var carLocation = dataCarsLocationByPassenger['message'][i];
// double distance1 = Geolocator.distanceBetween(
// mylocation.latitude,
// mylocation.longitude,
// double.parse(carLocation['latitude']),
// double.parse(carLocation['longitude']),
// );
// if (distance1 < nearestDistance) {
// nearestDistance = distance1;
// // nearestCarLocation = carLocation;
// nearestCar = CarLocation(
// distance: distance1,
// id: carLocation['driver_id'],
// latitude: double.parse(carLocation['latitude']),
// longitude: double.parse(carLocation['longitude']),
// );
// }
// isloading = true;
update();
// Make API request to get exact distance and duration
String apiUrl =
'${AppLink.googleMapsLink}distancematrix/json?destinations=${carLocation['latitude']},${carLocation['longitude']}&origins=${myLocation.latitude},${myLocation.longitude}&units=metric&key=${AK.mapAPIKEY}';
var response = await CRUD().getGoogleApi(link: apiUrl, payload: {});
if (response['status'] == "OK") {
var data = response;
// Extract distance and duration from the response and handle accordingly
int distance1 = data['rows'][0]['elements'][0]['distance']['value'];
distanceByPassenger =
data['rows'][0]['elements'][0]['distance']['text'];
duration1 = data['rows'][0]['elements'][0]['duration']['value'];
durationFromDriverToPassenger =
Duration(seconds: duration1.toInt());
newTime1 = currentTime.add(durationFromDriverToPassenger);
timeFromDriverToPassenger =
newTime1.add(Duration(minutes: 2.toInt()));
durationByPassenger =
data['rows'][0]['elements'][0]['duration']['text'];
// double distance1 = Geolocator.distanceBetween(
// mylocation.latitude,
// mylocation.longitude,
// double.parse(carLocation['latitude']),
// double.parse(carLocation['longitude']),
// );
// if (distance1 < nearestDistance) {
// nearestDistance = distance1;
// // nearestCarLocation = carLocation;
// nearestCar = CarLocation(
// distance: distance1,
// id: carLocation['driver_id'],
// latitude: double.parse(carLocation['latitude']),
// longitude: double.parse(carLocation['longitude']),
// );
// }
// isloading = true;
update();
if (distance1 < nearestDistance) {
nearestDistance = distance1.toDouble();
// Make API request to get exact distance and duration
String apiUrl =
'${AppLink.googleMapsLink}distancematrix/json?destinations=${carLocation['latitude']},${carLocation['longitude']}&origins=${myLocation.latitude},${myLocation.longitude}&units=metric&key=${AK.mapAPIKEY}';
var response = await CRUD().getGoogleApi(link: apiUrl, payload: {});
if (response['status'] == "OK") {
var data = response;
// Extract distance and duration from the response and handle accordingly
int distance1 =
data['rows'][0]['elements'][0]['distance']['value'];
distanceByPassenger =
data['rows'][0]['elements'][0]['distance']['text'];
duration1 = data['rows'][0]['elements'][0]['duration']['value'];
nearestCar = CarLocation(
distance: distance1.toDouble(),
duration: duration1.toDouble(),
id: carLocation['driver_id'],
latitude: double.parse(carLocation['latitude']),
longitude: double.parse(carLocation['longitude']),
);
// isloading = false;
durationFromDriverToPassenger =
Duration(seconds: duration1.toInt());
newTime1 = currentTime.add(durationFromDriverToPassenger);
timeFromDriverToPassenger =
newTime1.add(Duration(minutes: 2.toInt()));
durationByPassenger =
data['rows'][0]['elements'][0]['duration']['text'];
update();
}
}
if (distance1 < nearestDistance) {
nearestDistance = distance1.toDouble();
// Handle the distance and duration as needed
else {
print(
'Failed to retrieve distance and duration: ${response['status']}');
// Handle the failure case
nearestCar = CarLocation(
distance: distance1.toDouble(),
duration: duration1.toDouble(),
id: carLocation['driver_id'],
latitude: double.parse(carLocation['latitude']),
longitude: double.parse(carLocation['longitude']),
);
// isloading = false;
update();
}
}
// Handle the distance and duration as needed
else {
print(
'Failed to retrieve distance and duration: ${response['status']}');
// Handle the failure case
}
}
}
}