This commit is contained in:
Hamza-Ayed
2024-01-24 01:58:52 +03:00
parent 8aaca3630d
commit 1eab187076
13 changed files with 299 additions and 189 deletions

View File

@@ -213,9 +213,7 @@ class FirebaseMessagesController extends GetxController {
'notification': <String, dynamic>{ 'notification': <String, dynamic>{
'title': title, 'title': title,
'body': body, 'body': body,
'sound': Platform.isAndroid 'sound': 'tone2.wav'
? 'android/app/src/main/res/raw/tone1.mp3'
: 'tone2.wav'
}, },
'priority': 'high', 'priority': 'high',
'data': <String, dynamic>{ 'data': <String, dynamic>{
@@ -273,9 +271,7 @@ class FirebaseMessagesController extends GetxController {
'notification': <String, dynamic>{ 'notification': <String, dynamic>{
'title': title, 'title': title,
'body': body, 'body': body,
'sound': Platform.isAndroid 'sound': 'tone2.wav'
? 'android/app/src/main/res/raw/tone1.mp3'
: 'tone2.wav'
}, },
'data': { 'data': {
'passengerList': map, 'passengerList': map,
@@ -312,7 +308,7 @@ class FirebaseMessagesController extends GetxController {
'notification': <String, dynamic>{ 'notification': <String, dynamic>{
'title': title, 'title': title,
'body': body, 'body': body,
'sound': Platform.isAndroid ? 'tone2' : 'tone2.wav' 'sound': 'tone2.wav'
}, },
'data': <String, dynamic>{ 'data': <String, dynamic>{
'click_action': 'FLUTTER_NOTIFICATION_CLICK', 'click_action': 'FLUTTER_NOTIFICATION_CLICK',
@@ -352,9 +348,7 @@ class FirebaseMessagesController extends GetxController {
'title': title, 'title': title,
'body': body, 'body': body,
// 'sound': 'tone2.wav', // 'sound': 'tone2.wav',
'sound': Platform.isAndroid 'sound': 'order.wav'
? 'android/app/src/main/res/raw/tone1.mp3'
: 'tone2.wav'
}, },
'data': { 'data': {
'DriverList': data, 'DriverList': data,

View File

@@ -15,7 +15,7 @@ class LocationController extends GetxController {
late Location location; late Location location;
bool isLoading = false; bool isLoading = false;
bool isActive = false; bool isActive = false;
LatLng myLocation = const LatLng(32.3, 36.3); late LatLng myLocation;
String totalPoints = '0'; String totalPoints = '0';
LocationData? get currentLocation => _currentLocation; LocationData? get currentLocation => _currentLocation;
Timer? _locationTimer; Timer? _locationTimer;
@@ -24,9 +24,10 @@ class LocationController extends GetxController {
void onInit() async { void onInit() async {
super.onInit(); super.onInit();
location = Location(); location = Location();
getLocation();
// myLocation=getLocation();
totalPoints = Get.find<CaptainWalletController>().totalPoints; totalPoints = Get.find<CaptainWalletController>().totalPoints;
getLocation();
} }
void startLocationUpdates() async { void startLocationUpdates() async {

View File

@@ -27,7 +27,7 @@ class HomeCaptainController extends GetxController {
String totalMoneyInSEFER = '0'; String totalMoneyInSEFER = '0';
String totalDurationToday = '0'; String totalDurationToday = '0';
Timer? timer; Timer? timer;
late LatLng myLocation; late LatLng myLocation = const LatLng(32, 36);
String totalPoints = '0'; String totalPoints = '0';
String countRefuse = '0'; String countRefuse = '0';
bool mapType = false; bool mapType = false;
@@ -179,11 +179,19 @@ class HomeCaptainController extends GetxController {
timer?.cancel(); timer?.cancel();
} }
getlocation() async {
isLoading = true;
print('isLoading $isLoading');
update();
await Get.find<LocationController>().getLocation();
isLoading = false;
update();
}
@override @override
void onInit() async { void onInit() async {
await addToken(); await addToken();
// await Get.find<LocationController>().getLocation(); await getlocation();
onButtonSelected(); onButtonSelected();
getPaymentToday(); getPaymentToday();
getAllPayment(); getAllPayment();

View File

@@ -26,6 +26,9 @@ class MapDriverController extends GetxController {
List dataDestination = []; List dataDestination = [];
LatLngBounds? boundsData; LatLngBounds? boundsData;
BitmapDescriptor carIcon = BitmapDescriptor.defaultMarker; BitmapDescriptor carIcon = BitmapDescriptor.defaultMarker;
BitmapDescriptor passengerIcon = BitmapDescriptor.defaultMarker;
BitmapDescriptor startIcon = BitmapDescriptor.defaultMarker;
BitmapDescriptor endIcon = BitmapDescriptor.defaultMarker;
final List<LatLng> polylineCoordinates = []; final List<LatLng> polylineCoordinates = [];
final List<LatLng> polylineCoordinatesDestination = []; final List<LatLng> polylineCoordinatesDestination = [];
List<Polyline> polyLines = []; List<Polyline> polyLines = [];
@@ -75,6 +78,8 @@ class MapDriverController extends GetxController {
String? mapAPIKEY; String? mapAPIKEY;
final zones = <Zone>[]; final zones = <Zone>[];
String canelString = 'yet'; String canelString = 'yet';
late LatLng latLngpassengerLocation;
late LatLng latLngPassengerDestination;
void onMapCreated(GoogleMapController controller) async { void onMapCreated(GoogleMapController controller) async {
myLocation = Get.find<LocationController>().location as LatLng; myLocation = Get.find<LocationController>().location as LatLng;
@@ -229,6 +234,8 @@ class MapDriverController extends GetxController {
'driverID': box.read(BoxName.driverID).toString(), 'driverID': box.read(BoxName.driverID).toString(),
}); });
var d = jsonDecode(res); var d = jsonDecode(res);
mapController!.animateCamera(CameraUpdate.newLatLngZoom(myLocation, 18));
update();
print('...................'); print('...................');
print(d); print(d);
print('...................'); print('...................');
@@ -337,17 +344,55 @@ class MapDriverController extends GetxController {
} }
void addCustomCarIcon() { void addCustomCarIcon() {
ImageConfiguration config = const ImageConfiguration( ImageConfiguration config = ImageConfiguration(
size: Size(20, 20), size: const Size(30, 30), devicePixelRatio: Get.pixelRatio
// scale: 1.0, // scale: 1.0,
); );
BitmapDescriptor.fromAssetImage(config, 'assets/images/car.png') BitmapDescriptor.fromAssetImage(config, 'assets/images/car.png',
mipmaps: false)
.then((value) { .then((value) {
carIcon = value; carIcon = value;
update(); update();
}); });
} }
void addCustomStartIcon() async {
// Create the marker with the resized image
ImageConfiguration config = ImageConfiguration(
size: const Size(30, 30), devicePixelRatio: Get.pixelRatio);
BitmapDescriptor.fromAssetImage(config, 'assets/images/A.png',
mipmaps: false)
.then((value) {
startIcon = value;
update();
});
}
void addCustomEndIcon() {
ImageConfiguration config = ImageConfiguration(
size: const Size(30, 30), devicePixelRatio: Get.pixelRatio);
BitmapDescriptor.fromAssetImage(config, 'assets/images/b.png',
mipmaps: false)
.then((value) {
endIcon = value;
update();
});
}
void addCustomPassengerIcon() {
ImageConfiguration config = ImageConfiguration(
size: const Size(30, 30), devicePixelRatio: Get.pixelRatio
// scale: 1.0,
);
BitmapDescriptor.fromAssetImage(config, 'assets/images/picker.png',
mipmaps: false)
.then((value) {
passengerIcon = value;
update();
});
}
getMap(String origin, destination) async { getMap(String origin, destination) async {
isLoading = false; isLoading = false;
@@ -384,7 +429,7 @@ class MapDriverController extends GetxController {
width: 10, width: 10,
color: AppColor.blueColor, color: AppColor.blueColor,
); );
mapController!.animateCamera(CameraUpdate.newLatLngZoom(myLocation, 14));
polyLines.add(polyline); polyLines.add(polyline);
// rideConfirm = false; // rideConfirm = false;
update(); update();
@@ -406,7 +451,7 @@ class MapDriverController extends GetxController {
polylineCoordinatesDestination.add(LatLng(lat, lng)); polylineCoordinatesDestination.add(LatLng(lat, lng));
} }
if (polyLinesDestination.isNotEmpty) { if (polyLinesDestination.isNotEmpty) {
clearPolyline(); // clearPolyline();
var polyline = Polyline( var polyline = Polyline(
polylineId: PolylineId(response["routes"][0]["summary"]), polylineId: PolylineId(response["routes"][0]["summary"]),
points: polylineCoordinatesDestination, points: polylineCoordinatesDestination,
@@ -462,6 +507,19 @@ class MapDriverController extends GetxController {
step2 = Get.arguments['step2']; step2 = Get.arguments['step2'];
step3 = Get.arguments['step3']; step3 = Get.arguments['step3'];
step4 = Get.arguments['step4']; step4 = Get.arguments['step4'];
var coords = passengerLocation.split(',');
var coordDestination = passengerDestination.split(',');
// Parse to double
double latPassengerLocation = double.parse(coords[0]);
double lngPassengerLocation = double.parse(coords[1]);
double latPassengerDestination = double.parse(coordDestination[0]);
double lngPassengerDestination = double.parse(coordDestination[1]);
latLngpassengerLocation =
LatLng(latPassengerLocation, lngPassengerLocation);
latLngPassengerDestination =
LatLng(latPassengerDestination, lngPassengerDestination);
String lat = Get.find<LocationController>().myLocation.latitude.toString(); String lat = Get.find<LocationController>().myLocation.latitude.toString();
String lng = Get.find<LocationController>().myLocation.longitude.toString(); String lng = Get.find<LocationController>().myLocation.longitude.toString();
String origin = '$lat,$lng'; String origin = '$lat,$lng';
@@ -476,6 +534,9 @@ class MapDriverController extends GetxController {
) )
: await getMapDestination(passengerLocation, passengerDestination); : await getMapDestination(passengerLocation, passengerDestination);
addCustomCarIcon(); addCustomCarIcon();
addCustomPassengerIcon();
addCustomStartIcon();
addCustomEndIcon();
// updateMarker(); // updateMarker();
startTimerToShowPassengerInfoWindowFromDriver(); startTimerToShowPassengerInfoWindowFromDriver();
// cancelCheckRidefromPassenger(); // cancelCheckRidefromPassenger();

View File

@@ -23,6 +23,7 @@ import '../../views/widgets/elevated_btn.dart';
import '../firebase/firbase_messge.dart'; import '../firebase/firbase_messge.dart';
import '../functions/crud.dart'; import '../functions/crud.dart';
import '../functions/launch.dart'; import '../functions/launch.dart';
import '../functions/location_controller.dart';
import '../functions/secure_storage.dart'; import '../functions/secure_storage.dart';
import '../payment/payment_controller.dart'; import '../payment/payment_controller.dart';
@@ -59,7 +60,7 @@ class MapPassengerController extends GetxController {
LatLngBounds? boundsdata; LatLngBounds? boundsdata;
List<Marker> markers = []; List<Marker> markers = [];
List<Polyline> polyLines = []; List<Polyline> polyLines = [];
late LatLng myLocation; late LatLng passengerLocation = const LatLng(32, 34);
late LatLng newMyLocation = const LatLng(32.115295, 36.064773); late LatLng newMyLocation = const LatLng(32.115295, 36.064773);
late LatLng newStartPointLocation = const LatLng(32.115295, 36.064773); late LatLng newStartPointLocation = const LatLng(32.115295, 36.064773);
late LatLng newPointLocation0 = const LatLng(32.115295, 36.064773); late LatLng newPointLocation0 = const LatLng(32.115295, 36.064773);
@@ -205,8 +206,8 @@ class MapPassengerController extends GetxController {
currentLocationToFormPlaces = true; currentLocationToFormPlaces = true;
currentLocationString = 'Waiting for your location'.tr; currentLocationString = 'Waiting for your location'.tr;
await getLocation(); await getLocation();
currentLocationString = myLocation.toString(); currentLocationString = passengerLocation.toString();
newStartPointLocation = myLocation; newStartPointLocation = passengerLocation;
update(); update();
} }
@@ -215,6 +216,7 @@ class MapPassengerController extends GetxController {
clearPolyline(); clearPolyline();
isWayPointStopsSheetUtilGetMap = false; isWayPointStopsSheetUtilGetMap = false;
durationToRide = 0; durationToRide = 0;
distanceOfDestnation = 0;
wayPointSheetHeight = 0; wayPointSheetHeight = 0;
for (var i = 0; i < Get.find<WayPointController>().wayPoints.length; i++) { for (var i = 0; i < Get.find<WayPointController>().wayPoints.length; i++) {
if (placesCoordinate[i + 1].toString() != '') { if (placesCoordinate[i + 1].toString() != '') {
@@ -374,7 +376,7 @@ class MapPassengerController extends GetxController {
// Format the message. // Format the message.
String message = String message =
'Hi! This is ${box.read(BoxName.name)}. I am using ${box.read(AppInformation.appName)} to ride with ${dataCarsLocationByPassenger['message'][carsOrder]['first_name'].toString()} as the driver. ${dataCarsLocationByPassenger['message'][carsOrder]['first_name'].toString()} is driving a ${dataCarsLocationByPassenger['message'][carsOrder]['model'].toString()} with license plate ${dataCarsLocationByPassenger['message'][carsOrder]['license_plate'].toString()}. I am currently located at $myLocation. If you need to reach me, please contact the driver directly at $driverPhone.'; 'Hi! This is ${box.read(BoxName.name)}. I am using ${box.read(AppInformation.appName)} to ride with ${dataCarsLocationByPassenger['message'][carsOrder]['first_name'].toString()} as the driver. ${dataCarsLocationByPassenger['message'][carsOrder]['first_name'].toString()} is driving a ${dataCarsLocationByPassenger['message'][carsOrder]['model'].toString()} with license plate ${dataCarsLocationByPassenger['message'][carsOrder]['license_plate'].toString()}. I am currently located at $passengerLocation. If you need to reach me, please contact the driver directly at $driverPhone.';
// Launch the URL to send the SMS. // Launch the URL to send the SMS.
launchCommunication('sms', to, message); launchCommunication('sms', to, message);
@@ -387,7 +389,7 @@ class MapPassengerController extends GetxController {
// Format the message. // Format the message.
String message = String message =
'Hi! This is ${box.read(BoxName.name)}.\n I am using ${box.read(AppInformation.appName)} to ride with ${dataCarsLocationByPassenger['message'][carsOrder]['first_name'].toString()} as the driver. ${dataCarsLocationByPassenger['message'][carsOrder]['first_name'].toString()} \nis driving a ${dataCarsLocationByPassenger['message'][carsOrder]['model'].toString()}\n with license plate ${dataCarsLocationByPassenger['message'][carsOrder]['license_plate'].toString()}.\n I am currently located at $myLocation.\n If you need to reach me, please contact the driver directly at\n\n $driverPhone.'; 'Hi! This is ${box.read(BoxName.name)}.\n I am using ${box.read(AppInformation.appName)} to ride with ${dataCarsLocationByPassenger['message'][carsOrder]['first_name'].toString()} as the driver. ${dataCarsLocationByPassenger['message'][carsOrder]['first_name'].toString()} \nis driving a ${dataCarsLocationByPassenger['message'][carsOrder]['model'].toString()}\n with license plate ${dataCarsLocationByPassenger['message'][carsOrder]['license_plate'].toString()}.\n I am currently located at $passengerLocation.\n If you need to reach me, please contact the driver directly at\n\n $driverPhone.';
// Launch the URL to send the SMS. // Launch the URL to send the SMS.
launchCommunication('whatsapp', to, message); launchCommunication('whatsapp', to, message);
@@ -727,8 +729,8 @@ class MapPassengerController extends GetxController {
Future getCarsLocationByPassenger() async { Future getCarsLocationByPassenger() async {
// if (rideConfirm == false) { // if (rideConfirm == false) {
carsLocationByPassenger = []; carsLocationByPassenger = [];
LatLngBounds bounds = LatLngBounds bounds = calculateBounds(
calculateBounds(myLocation.latitude, myLocation.longitude, 8000); passengerLocation.latitude, passengerLocation.longitude, 8000);
print( print(
'Southwest: ${bounds.southwest.latitude}, ${bounds.southwest.longitude}'); 'Southwest: ${bounds.southwest.latitude}, ${bounds.southwest.longitude}');
print( print(
@@ -852,7 +854,7 @@ class MapPassengerController extends GetxController {
shouldFetch = false; shouldFetch = false;
isPassengerChosen = false; isPassengerChosen = false;
isCashConfirmPageShown = false; isCashConfirmPageShown = false;
totalStepDurations = 0; // totalStepDurations = 0;
isCashSelectedBeforeConfirmRide = false; isCashSelectedBeforeConfirmRide = false;
timeToPassengerFromDriverAfterApplied = 0; timeToPassengerFromDriverAfterApplied = 0;
changeCancelRidePageShow(); changeCancelRidePageShow();
@@ -883,7 +885,9 @@ class MapPassengerController extends GetxController {
isPassengerChosen = false; isPassengerChosen = false;
isCashSelectedBeforeConfirmRide = false; isCashSelectedBeforeConfirmRide = false;
isPickerShown = false; isPickerShown = false;
totalStepDurations = 0; haveSteps = false;
isMarkersShown = false;
// totalStepDurations = 0;
timeToPassengerFromDriverAfterApplied = 0; timeToPassengerFromDriverAfterApplied = 0;
update(); update();
} else { } else {
@@ -900,10 +904,12 @@ class MapPassengerController extends GetxController {
rideConfirm = false; rideConfirm = false;
shouldFetch = false; shouldFetch = false;
isPassengerChosen = false; isPassengerChosen = false;
haveSteps = false;
isMarkersShown = false;
isCashConfirmPageShown = false; isCashConfirmPageShown = false;
isCashSelectedBeforeConfirmRide = false; isCashSelectedBeforeConfirmRide = false;
timeToPassengerFromDriverAfterApplied = 0; timeToPassengerFromDriverAfterApplied = 0;
totalStepDurations = 0; // totalStepDurations = 0;
changeCancelRidePageShow(); changeCancelRidePageShow();
clearPolyline(); clearPolyline();
remainingTime = 0; remainingTime = 0;
@@ -1040,7 +1046,7 @@ class MapPassengerController extends GetxController {
Future getPlaces() async { Future getPlaces() async {
var url = var url =
// '${AppLink.googleMapsLink}place/nearbysearch/json?location=${mylocation.longitude}&radius=25000&language=ar&keyword=&key=${placeController.text}${AK.mapAPIKEY}'; // '${AppLink.googleMapsLink}place/nearbysearch/json?location=${mylocation.longitude}&radius=25000&language=ar&keyword=&key=${placeController.text}${AK.mapAPIKEY}';
'${AppLink.googleMapsLink}place/nearbysearch/json?keyword=${placeDestinationController.text}&location=${myLocation.latitude},${myLocation.longitude}&radius=50000&language=en&key=${AK.mapAPIKEY.toString()}'; '${AppLink.googleMapsLink}place/nearbysearch/json?keyword=${placeDestinationController.text}&location=${passengerLocation.latitude},${passengerLocation.longitude}&radius=50000&language=en&key=${AK.mapAPIKEY.toString()}';
var response = await CRUD().getGoogleApi(link: url, payload: {}); var response = await CRUD().getGoogleApi(link: url, payload: {});
@@ -1052,7 +1058,7 @@ class MapPassengerController extends GetxController {
Future getPlacesStart() async { Future getPlacesStart() async {
var url = var url =
// '${AppLink.googleMapsLink}place/nearbysearch/json?location=${mylocation.longitude}&radius=25000&language=ar&keyword=&key=${placeController.text}${AK.mapAPIKEY}'; // '${AppLink.googleMapsLink}place/nearbysearch/json?location=${mylocation.longitude}&radius=25000&language=ar&keyword=&key=${placeController.text}${AK.mapAPIKEY}';
'${AppLink.googleMapsLink}place/nearbysearch/json?keyword=${placeStartController.text}&location=${myLocation.latitude},${myLocation.longitude}&radius=50000&language=en&key=${AK.mapAPIKEY.toString()}'; '${AppLink.googleMapsLink}place/nearbysearch/json?keyword=${placeStartController.text}&location=${passengerLocation.latitude},${passengerLocation.longitude}&radius=50000&language=en&key=${AK.mapAPIKEY.toString()}';
var response = await CRUD().getGoogleApi(link: url, payload: {}); var response = await CRUD().getGoogleApi(link: url, payload: {});
@@ -1063,7 +1069,7 @@ class MapPassengerController extends GetxController {
Future getPlacesListsWayPoint(int index) async { Future getPlacesListsWayPoint(int index) async {
var url = var url =
'${AppLink.googleMapsLink}place/nearbysearch/json?keyword=${wayPoint0Controller.text}&location=${myLocation.latitude},${myLocation.longitude}&radius=50000&language=en&key=${AK.mapAPIKEY.toString()}'; '${AppLink.googleMapsLink}place/nearbysearch/json?keyword=${wayPoint0Controller.text}&location=${passengerLocation.latitude},${passengerLocation.longitude}&radius=50000&language=en&key=${AK.mapAPIKEY.toString()}';
var response = await CRUD().getGoogleApi(link: url, payload: {}); var response = await CRUD().getGoogleApi(link: url, payload: {});
@@ -1176,7 +1182,7 @@ class MapPassengerController extends GetxController {
// Get the current location // Get the current location
LocationData _locationData = await location.getLocation(); LocationData _locationData = await location.getLocation();
myLocation = passengerLocation =
(_locationData.latitude != null && _locationData.longitude != null (_locationData.latitude != null && _locationData.longitude != null
? LatLng(_locationData.latitude!, _locationData.longitude!) ? LatLng(_locationData.latitude!, _locationData.longitude!)
: null)!; : null)!;
@@ -1209,10 +1215,12 @@ class MapPassengerController extends GetxController {
GoogleMapController? mapController; GoogleMapController? mapController;
void onMapCreated(GoogleMapController controller) { void onMapCreated(GoogleMapController controller) {
// myLocation = Get.find<LocationController>().location as LatLng;
// myLocation = myLocation;
mapController = controller; mapController = controller;
controller.getVisibleRegion(); controller.getVisibleRegion();
controller.animateCamera( controller.animateCamera(
CameraUpdate.newLatLng(myLocation), CameraUpdate.newLatLng(passengerLocation),
); );
update(); update();
} }
@@ -1275,7 +1283,7 @@ class MapPassengerController extends GetxController {
// Update the map with the new markers // Update the map with the new markers
mapController?.animateCamera(CameraUpdate.newLatLng( mapController?.animateCamera(CameraUpdate.newLatLng(
LatLng(myLocation.latitude, myLocation.longitude))); LatLng(passengerLocation.latitude, passengerLocation.longitude)));
} }
String durationByPassenger = ''; String durationByPassenger = '';
@@ -1288,71 +1296,74 @@ class MapPassengerController extends GetxController {
if (polyLines.isEmpty || data.isEmpty) { if (polyLines.isEmpty || data.isEmpty) {
if (rideConfirm == false) { if (rideConfirm == false) {
double nearestDistance = double.infinity; double nearestDistance = double.infinity;
if (dataCarsLocationByPassenger['message'].length > 0) { if (dataCarsLocationByPassenger != 'failure') {
for (var i = 0; if (dataCarsLocationByPassenger['message'].length > 0) {
i < dataCarsLocationByPassenger['message'].length; for (var i = 0;
i++) { i < dataCarsLocationByPassenger['message'].length;
var carLocation = dataCarsLocationByPassenger['message'][i]; i++) {
var carLocation = dataCarsLocationByPassenger['message'][i];
// double distance1 = Geolocator.distanceBetween( // double distance1 = Geolocator.distanceBetween(
// mylocation.latitude, // mylocation.latitude,
// mylocation.longitude, // mylocation.longitude,
// double.parse(carLocation['latitude']), // double.parse(carLocation['latitude']),
// double.parse(carLocation['longitude']), // double.parse(carLocation['longitude']),
// ); // );
// if (distance1 < nearestDistance) { // if (distance1 < nearestDistance) {
// nearestDistance = distance1; // nearestDistance = distance1;
// // nearestCarLocation = carLocation; // // nearestCarLocation = carLocation;
// nearestCar = CarLocation( // nearestCar = CarLocation(
// distance: distance1, // distance: distance1,
// id: carLocation['driver_id'], // id: carLocation['driver_id'],
// latitude: double.parse(carLocation['latitude']), // latitude: double.parse(carLocation['latitude']),
// longitude: double.parse(carLocation['longitude']), // longitude: double.parse(carLocation['longitude']),
// ); // );
// } // }
// isloading = true; // 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'];
update(); update();
if (distance1 < nearestDistance) { // Make API request to get exact distance and duration
nearestDistance = distance1.toDouble(); String apiUrl =
'${AppLink.googleMapsLink}distancematrix/json?destinations=${carLocation['latitude']},${carLocation['longitude']}&origins=${passengerLocation.latitude},${passengerLocation.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( durationFromDriverToPassenger =
distance: distance1.toDouble(), Duration(seconds: duration1.toInt());
duration: duration1.toDouble(), newTime1 = currentTime.add(durationFromDriverToPassenger);
id: carLocation['driver_id'], timeFromDriverToPassenger =
latitude: double.parse(carLocation['latitude']), newTime1.add(Duration(minutes: 2.toInt()));
longitude: double.parse(carLocation['longitude']), durationByPassenger =
); data['rows'][0]['elements'][0]['duration']['text'];
// isloading = false;
update(); update();
} if (distance1 < nearestDistance) {
} nearestDistance = distance1.toDouble();
// Handle the distance and duration as needed nearestCar = CarLocation(
else { distance: distance1.toDouble(),
print( duration: duration1.toDouble(),
'Failed to retrieve distance and duration: ${response['status']}'); id: carLocation['driver_id'],
// Handle the failure case 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
}
} }
} }
} }
@@ -1369,6 +1380,11 @@ class MapPassengerController extends GetxController {
getMap(String origin, destination) async { getMap(String origin, destination) async {
await getCarsLocationByPassenger(); await getCarsLocationByPassenger();
// print(carsLocationByPassenger); // print(carsLocationByPassenger);
var coordDestination = destination.split(',');
double latPassengerDestination = double.parse(coordDestination[0]);
double lngPassengerDestination = double.parse(coordDestination[1]);
myDestination = LatLng(latPassengerDestination, lngPassengerDestination);
isLoading = false; isLoading = false;
update(); update();
var url = var url =
@@ -1405,17 +1421,23 @@ class MapPassengerController extends GetxController {
// Animate the camera to the adjusted bounds // Animate the camera to the adjusted bounds
if (distanceOfDestnation <= 5) { if (distanceOfDestnation <= 5) {
mapController!.animateCamera(CameraUpdate.newLatLngZoom(myLocation, 14)); mapController!
.animateCamera(CameraUpdate.newLatLngZoom(newStartPointLocation, 14));
} else if (distanceOfDestnation > 5 && distanceOfDestnation <= 8) { } else if (distanceOfDestnation > 5 && distanceOfDestnation <= 8) {
mapController!.animateCamera(CameraUpdate.newLatLngZoom(myLocation, 13)); mapController!
.animateCamera(CameraUpdate.newLatLngZoom(newStartPointLocation, 13));
} else if (distanceOfDestnation > 8 && distanceOfDestnation < 16) { } else if (distanceOfDestnation > 8 && distanceOfDestnation < 16) {
mapController!.animateCamera(CameraUpdate.newLatLngZoom(myLocation, 12)); mapController!
.animateCamera(CameraUpdate.newLatLngZoom(newStartPointLocation, 12));
} else if (distanceOfDestnation >= 16 && distanceOfDestnation < 30) { } else if (distanceOfDestnation >= 16 && distanceOfDestnation < 30) {
mapController!.animateCamera(CameraUpdate.newLatLngZoom(myLocation, 11)); mapController!
.animateCamera(CameraUpdate.newLatLngZoom(newStartPointLocation, 11));
} else if (distanceOfDestnation >= 30 && distanceOfDestnation < 100) { } else if (distanceOfDestnation >= 30 && distanceOfDestnation < 100) {
mapController!.animateCamera(CameraUpdate.newLatLngZoom(myLocation, 10)); mapController!
.animateCamera(CameraUpdate.newLatLngZoom(newStartPointLocation, 10));
} else if (distanceOfDestnation >= 100) { } else if (distanceOfDestnation >= 100) {
mapController!.animateCamera(CameraUpdate.newLatLngZoom(myLocation, 7)); mapController!
.animateCamera(CameraUpdate.newLatLngZoom(newStartPointLocation, 7));
} }
if (polyLines.isNotEmpty) { if (polyLines.isNotEmpty) {
clearPolyline(); clearPolyline();
@@ -1434,25 +1456,30 @@ class MapPassengerController extends GetxController {
} }
} }
int totalStepDurations = 0; double distanceOfDestnation = 0;
getMapPoints(String origin, String destination, int index) async { bool haveSteps = false;
getMapPoints(String originSteps, String destinationSteps, int index) async {
isWayPointStopsSheetUtilGetMap = false; isWayPointStopsSheetUtilGetMap = false;
haveSteps = true;
await getCarsLocationByPassenger(); await getCarsLocationByPassenger();
isLoading = false; // isLoading = true;
update(); update();
var url = var url =
('${AppLink.googleMapsLink}directions/json?&language=en&avoid=tolls|ferries&destination=$destination&origin=$origin&key=${AK.mapAPIKEY}'); ('${AppLink.googleMapsLink}directions/json?&language=en&avoid=tolls|ferries&destination=$destinationSteps&origin=$originSteps&key=${AK.mapAPIKEY}');
// print(url); // print(url);
var response = await CRUD().getGoogleApi(link: url, payload: {}); var response = await CRUD().getGoogleApi(link: url, payload: {});
data = response['routes'][0]['legs']; data = response['routes'][0]['legs'];
// print(data); // print(data);
isLoading = false; // isLoading = false;
int durationToRide0 = data[0]['duration']['value']; int durationToRide0 = data[0]['duration']['value'];
durationToRide = durationToRide + durationToRide0; durationToRide = durationToRide + durationToRide0;
print('durationToRide is ${data[0]['duration']['value']}'); print('durationToRide is ${data[0]['duration']['value']}');
print('totalStepDurations is $durationToRide'); print('totalStepDurations is $durationToRide');
double distanceToRide0 = (data[0]['distance']['value']) / 1000;
distanceOfDestnation = distanceOfDestnation + distanceToRide0;
print('distanceToRide is $distanceToRide0');
print('totalStepdistance is $distanceOfDestnation');
update(); update();
final points = final points =
decodePolyline(response["routes"][0]["overview_polyline"]["points"]); decodePolyline(response["routes"][0]["overview_polyline"]["points"]);
@@ -1474,22 +1501,28 @@ class MapPassengerController extends GetxController {
// Calculate the zoom level based on the distance and screen size // Calculate the zoom level based on the distance and screen size
double distanceOfDestnation = // double distanceOfDestnation =
getDistanceFromText(data[0]['distance']['text']); // getDistanceFromText(data[0]['distance']['text']);
// Animate the camera to the adjusted bounds // Animate the camera to the adjusted bounds
if (distanceOfDestnation <= 5) { if (distanceOfDestnation <= 5) {
mapController!.animateCamera(CameraUpdate.newLatLngZoom(myLocation, 15)); mapController!
.animateCamera(CameraUpdate.newLatLngZoom(newPointLocation0, 14));
} else if (distanceOfDestnation > 5 && distanceOfDestnation <= 8) { } else if (distanceOfDestnation > 5 && distanceOfDestnation <= 8) {
mapController!.animateCamera(CameraUpdate.newLatLngZoom(myLocation, 14)); mapController!
.animateCamera(CameraUpdate.newLatLngZoom(newPointLocation0, 13));
} else if (distanceOfDestnation > 8 && distanceOfDestnation < 16) { } else if (distanceOfDestnation > 8 && distanceOfDestnation < 16) {
mapController!.animateCamera(CameraUpdate.newLatLngZoom(myLocation, 13)); mapController!
.animateCamera(CameraUpdate.newLatLngZoom(newPointLocation0, 12));
} else if (distanceOfDestnation >= 16 && distanceOfDestnation < 30) { } else if (distanceOfDestnation >= 16 && distanceOfDestnation < 30) {
mapController!.animateCamera(CameraUpdate.newLatLngZoom(myLocation, 11)); mapController!
.animateCamera(CameraUpdate.newLatLngZoom(newPointLocation0, 8));
} else if (distanceOfDestnation >= 30 && distanceOfDestnation < 100) { } else if (distanceOfDestnation >= 30 && distanceOfDestnation < 100) {
mapController!.animateCamera(CameraUpdate.newLatLngZoom(myLocation, 9)); mapController!
.animateCamera(CameraUpdate.newLatLngZoom(newPointLocation0, 6));
} else if (distanceOfDestnation >= 100) { } else if (distanceOfDestnation >= 100) {
mapController!.animateCamera(CameraUpdate.newLatLngZoom(myLocation, 7)); mapController!
.animateCamera(CameraUpdate.newLatLngZoom(newPointLocation0, 5));
} }
if (polyLines.isNotEmpty) { if (polyLines.isNotEmpty) {
// clearPolyline(); // clearPolyline();
@@ -1503,7 +1536,7 @@ class MapPassengerController extends GetxController {
polyLines.add(polyline); polyLines.add(polyline);
rideConfirm = false; rideConfirm = false;
isMarkersShown = true; // isMarkersShown = true;
update(); update();
} }
} }

View File

@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:ride/constant/style.dart'; import 'package:ride/constant/style.dart';
import 'package:ride/controller/home/map_passenger_controller.dart';
import '../../constant/api_key.dart'; import '../../constant/api_key.dart';
import '../../constant/links.dart'; import '../../constant/links.dart';
@@ -121,7 +122,7 @@ class WayPointController extends GetxController {
void onInit() { void onInit() {
Get.put(LocationController()); Get.put(LocationController());
addWayPoints(); addWayPoints();
myLocation = Get.find<LocationController>().myLocation; myLocation = Get.find<MapPassengerController>().passengerLocation;
super.onInit(); super.onInit();
} }
} }

View File

@@ -3,6 +3,7 @@ import 'package:get/get.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:flutter_font_icons/flutter_font_icons.dart'; import 'package:flutter_font_icons/flutter_font_icons.dart';
import 'package:ride/views/home/Captin/home_captain/drawer_captain.dart'; import 'package:ride/views/home/Captin/home_captain/drawer_captain.dart';
import 'package:ride/views/widgets/mycircular.dart';
import '../../../../constant/colors.dart'; import '../../../../constant/colors.dart';
import '../../../../constant/info.dart'; import '../../../../constant/info.dart';
@@ -19,14 +20,14 @@ import '../../../widgets/circle_container.dart';
class HomeCaptain extends StatelessWidget { class HomeCaptain extends StatelessWidget {
HomeCaptain({super.key}); HomeCaptain({super.key});
final LocationController locationController = LocationController(); final LocationController locationController = Get.put(LocationController());
// final HomeCaptainController homeCaptainController = HomeCaptainController(); // final HomeCaptainController homeCaptainController = HomeCaptainController();
// final LocationController locationController=LocationController(); // final LocationController locationController=LocationController();
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
Get.put(OrderRequestController()); Get.put(OrderRequestController());
Get.put(HomeCaptainController()); Get.put(HomeCaptainController());
// Get.put(HomeCaptainController()); Get.put(LocationController());
print('local is ${Get.find<LocaleController>().language!.countryCode}'); print('local is ${Get.find<LocaleController>().language!.countryCode}');
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
@@ -64,28 +65,31 @@ class HomeCaptain extends StatelessWidget {
body: Stack( body: Stack(
children: [ children: [
GetBuilder<HomeCaptainController>( GetBuilder<HomeCaptainController>(
builder: (controller) => GoogleMap( builder: (controller) => controller.isLoading
onMapCreated: controller.onMapCreated, ? const MyCircularProgressIndicator()
// cameraTargetBounds: CameraTargetBounds(controller.boundsdata), : GoogleMap(
minMaxZoomPreference: const MinMaxZoomPreference(6, 18), onMapCreated: controller.onMapCreated,
// cameraTargetBounds: CameraTargetBounds(controller.boundsdata),
minMaxZoomPreference: const MinMaxZoomPreference(6, 18),
initialCameraPosition: CameraPosition( initialCameraPosition: CameraPosition(
target: locationController.myLocation, target: locationController.myLocation,
zoom: 15, zoom: 15,
), ),
mapType: controller.mapType ? MapType.satellite : MapType.normal, mapType:
myLocationButtonEnabled: true, controller.mapType ? MapType.satellite : MapType.normal,
// liteModeEnabled: true, tiltGesturesEnabled: false, myLocationButtonEnabled: true,
// liteModeEnabled: true, tiltGesturesEnabled: false,
// indoorViewEnabled: true, // indoorViewEnabled: true,
trafficEnabled: controller.mapTrafficON, trafficEnabled: controller.mapTrafficON,
buildingsEnabled: true, buildingsEnabled: true,
mapToolbarEnabled: true, mapToolbarEnabled: true,
myLocationEnabled: true, myLocationEnabled: true,
// liteModeEnabled: true, // liteModeEnabled: true,
), ),
), ),
Positioned( Positioned(
bottom: 10, bottom: 10,

View File

@@ -25,10 +25,10 @@ class GoogleDriverMap extends StatelessWidget {
target: locationController.myLocation, target: locationController.myLocation,
zoom: 15, zoom: 15,
), ),
// onCameraMove: (position) { onCameraMove: (position) {
// locationController.myLocation = position.target; locationController.myLocation = position.target;
// print(position); print(position);
// }, },
minMaxZoomPreference: const MinMaxZoomPreference(6, 18), minMaxZoomPreference: const MinMaxZoomPreference(6, 18),
buildingsEnabled: true, buildingsEnabled: true,
mapToolbarEnabled: true, mapToolbarEnabled: true,
@@ -40,7 +40,7 @@ class GoogleDriverMap extends StatelessWidget {
endCap: Cap.buttCap, endCap: Cap.buttCap,
startCap: Cap.buttCap, startCap: Cap.buttCap,
visible: true, visible: true,
polylineId: const PolylineId('route'), polylineId: const PolylineId('route1'),
points: controller.polylineCoordinates, points: controller.polylineCoordinates,
color: AppColor.greenColor, color: AppColor.greenColor,
width: 5, width: 5,
@@ -64,11 +64,18 @@ class GoogleDriverMap extends StatelessWidget {
position: locationController.myLocation, position: locationController.myLocation,
draggable: true, draggable: true,
icon: controller.carIcon, icon: controller.carIcon,
infoWindow: const InfoWindow( ),
title: 'Time', Marker(
// snippet: controller.durationFromDriverToPassenger markerId: MarkerId('start'.tr),
// .toString(), position: controller.latLngpassengerLocation,
), draggable: true,
icon: controller.startIcon,
),
Marker(
markerId: MarkerId('end'.tr),
position: controller.latLngPassengerDestination,
draggable: true,
icon: controller.endIcon,
), ),
}, },
), ),

View File

@@ -82,7 +82,7 @@ GetBuilder<MapPassengerController> formSearchPlaces() {
controller.changeHeightPlaces(); controller.changeHeightPlaces();
controller.myLocation = controller.newMyLocation; controller.passengerLocation = controller.newMyLocation;
controller.convertHintTextDestinationNewPlaces(index); controller.convertHintTextDestinationNewPlaces(index);
controller.placesDestination = []; controller.placesDestination = [];

View File

@@ -87,9 +87,9 @@ GetBuilder<MapPassengerController> formSearchPlaces(int index) {
if (controller.currentLocationToFormPlacesAll[index] == if (controller.currentLocationToFormPlacesAll[index] ==
true) { true) {
controller.newStartPointLocation = controller.newStartPointLocation =
controller.myLocation; controller.passengerLocation;
} else { } else {
controller.myLocation = controller.passengerLocation =
controller.newStartPointLocation; controller.newStartPointLocation;
} }

View File

@@ -37,7 +37,7 @@ class GoogleMapPassengerWidget extends StatelessWidget {
controller.clearPolyline(); controller.clearPolyline();
if (controller.dataCarsLocationByPassenger != null) { if (controller.dataCarsLocationByPassenger != null) {
await controller.getMap( await controller.getMap(
'${controller.myLocation.latitude},${controller.myLocation.longitude}', '${controller.passengerLocation.latitude},${controller.passengerLocation.longitude}',
'${argument.latitude.toString()},${argument.longitude.toString()}'); '${argument.latitude.toString()},${argument.longitude.toString()}');
Get.back(); Get.back();
@@ -131,7 +131,7 @@ class GoogleMapPassengerWidget extends StatelessWidget {
// controller.bottomSheet(); // controller.bottomSheet();
}, },
initialCameraPosition: CameraPosition( initialCameraPosition: CameraPosition(
target: controller.myLocation, target: controller.passengerLocation,
zoom: 15, zoom: 15,
), ),
markers: { markers: {
@@ -154,43 +154,44 @@ class GoogleMapPassengerWidget extends StatelessWidget {
position: controller.newStartPointLocation, position: controller.newStartPointLocation,
draggable: true, draggable: true,
icon: controller.startIcon, icon: controller.startIcon,
infoWindow: const InfoWindow(
title: 'Time',
anchor: Offset(0.5, 0.5), // Adjust the anchor as needed
// snippet: controller.durationFromDriverToPassenger
// .toString(),
),
onDragEnd: (value) {
print(value);
},
// infoWindow: InfoWindow(title: 'my location'.tr),
), ),
if (controller.isMarkersShown) if (controller.isMarkersShown)
Marker( Marker(
markerId: MarkerId('Destination'.tr), markerId: MarkerId('Destination'.tr),
position: controller.newMyLocation, position: controller.myDestination,
draggable: true,
icon: controller.endIcon,
),
if (controller.haveSteps)
Marker(
markerId: MarkerId('StartSteps'.tr),
position: LatLng(
double.parse(
controller.placesCoordinate[0].split(',')[0]),
double.parse(
controller.placesCoordinate[0].split(',')[1])),
draggable: true,
icon: controller.startIcon,
),
if (controller.haveSteps)
Marker(
markerId: MarkerId('EndSteps'.tr),
position: controller.newPointLocation4 == ''
? LatLng(
double.parse(
controller.placesCoordinate[3].split(',')[0]),
double.parse(
controller.placesCoordinate[3].split(',')[1]))
: controller.newPointLocation3 == ''
? LatLng(
double.parse(controller.placesCoordinate[2]
.split(',')[0]),
double.parse(controller.placesCoordinate[2]
.split(',')[1]))
: controller.newPointLocation2,
draggable: true, draggable: true,
icon: controller.endIcon, icon: controller.endIcon,
infoWindow: InfoWindow(
anchor: const Offset(0.5, 0),
title: 'Time',
snippet: controller.durationByPassenger.toString()
// snippet: controller.durationFromDriverToPassenger
// .toString(),
),
onDragEnd: (value) {
print(value);
},
// infoWindow: InfoWindow(title: 'my location'.tr),
), ),
// Marker(
// markerId: MarkerId('Target'.tr),
// position: controller.myDestination,
// draggable: true,
// onDragEnd: (v) {
// print(v);
// },
// ),
}, },
polylines: { polylines: {
Polyline( Polyline(
@@ -283,7 +284,7 @@ class GoogleMapPassengerWidget extends StatelessWidget {
circles: <Circle>{ circles: <Circle>{
Circle( Circle(
circleId: const CircleId('circle_id'), circleId: const CircleId('circle_id'),
center: controller.myLocation, center: controller.passengerLocation,
radius: 100, radius: 100,
fillColor: Colors.blue.withOpacity(0.3), fillColor: Colors.blue.withOpacity(0.3),
strokeColor: Colors.blue, strokeColor: Colors.blue,

View File

@@ -348,7 +348,7 @@ class FavioratePlacesDialogu extends StatelessWidget {
Get.back(); Get.back();
await controller.getLocation(); await controller.getLocation();
await controller.getMap( await controller.getMap(
'${controller.myLocation.latitude},${controller.myLocation.longitude}', '${controller.passengerLocation.latitude},${controller.passengerLocation.longitude}',
'${favoritePlaces[index]['latitude']},${favoritePlaces[index]['longitude']}', '${favoritePlaces[index]['latitude']},${favoritePlaces[index]['longitude']}',
); );
// controller.changePickerShown(); // controller.changePickerShown();

View File

@@ -135,7 +135,7 @@ class PickerAnimtionContainerFormPlaces extends StatelessWidget {
onPressed: () async { onPressed: () async {
await controller await controller
.getMap( .getMap(
'${controller.myLocation.latitude},${controller.myLocation.longitude}', '${controller.passengerLocation.latitude},${controller.passengerLocation.longitude}',
'${favoritePlaces[index]['latitude']},${favoritePlaces[index]['longitude']}', '${favoritePlaces[index]['latitude']},${favoritePlaces[index]['longitude']}',
); );
controller controller
@@ -193,7 +193,7 @@ class PickerAnimtionContainerFormPlaces extends StatelessWidget {
title: 'Go to this Target'.tr, title: 'Go to this Target'.tr,
onPressed: () async { onPressed: () async {
await controller.getMap( await controller.getMap(
'${controller.myLocation.latitude},${controller.myLocation.longitude}', '${controller.passengerLocation.latitude},${controller.passengerLocation.longitude}',
'${controller.newMyLocation.latitude},${controller.newMyLocation.longitude}', '${controller.newMyLocation.latitude},${controller.newMyLocation.longitude}',
); );
controller.changePickerShown(); controller.changePickerShown();