This commit is contained in:
Hamza-Ayed
2023-08-24 18:29:47 +03:00
parent c1869d2725
commit 63770619d6
48 changed files with 400 additions and 206 deletions

View File

@@ -1,6 +1,8 @@
import 'dart:async';
import 'dart:convert';
import 'dart:math' show sqrt, pi, cos, sin;
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:get/get.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:google_polyline_algorithm/google_polyline_algorithm.dart';
@@ -9,10 +11,9 @@ import 'package:ride/constant/box_name.dart';
import 'package:ride/constant/credential.dart';
import 'package:ride/constant/links.dart';
import 'package:ride/controller/functions/crud.dart';
import 'package:http/http.dart' as http;
import 'package:ride/views/widgets/elevated_btn.dart';
import '../../main.dart';
import '../../models/model/locations.dart';
import '../firebase/firbase_messge.dart';
class MapController extends GetxController {
bool isloading = true;
@@ -27,7 +28,7 @@ class MapController extends GetxController {
late LatLng newMylocation = const LatLng(32.115295, 36.064773);
LatLng mydestination = const LatLng(32.115295, 36.064773);
final List<LatLng> polylineCoordinates = [];
final List<LatLng> carsLocationByPassenger = [];
List<LatLng> carsLocationByPassenger = [];
BitmapDescriptor markerIcon = BitmapDescriptor.defaultMarker;
BitmapDescriptor carIcon = BitmapDescriptor.defaultMarker;
double height = 150;
@@ -43,14 +44,17 @@ class MapController extends GetxController {
bool isCancelRidePageShown = false;
bool isCashConfirmPageShown = false;
bool isPaymentMethodPageShown = false;
bool rideConfirm = false;
bool isMainBottomMenuMap = true;
double heightButtomSheetShown = 0;
double cashConfirmPageShown = 250;
double paymentPageShown = Get.height * .6;
late final LatLng southwest;
late final LatLng northeast;
late LatLng southwest;
late LatLng northeast;
List<CarLocationModel> carLocations = <CarLocationModel>[];
var dataCarsLocationByPassenger;
CarLocation? nearestCar;
late Timer markerReloadingTimer;
// final mainBottomMenuMap = GlobalKey<AnimatedContainer>();
void changeButtomSheetShown() {
isButtomSheetShown = !isButtomSheetShown;
@@ -103,24 +107,15 @@ class MapController extends GetxController {
update();
}
bool rideConfirm = false;
changeConfirmRide() {
rideConfirm = true;
print('rideConfirm= $rideConfirm');
//TODO add ride and get ride id and details
update();
}
Future cancelRide() async {
var payload = {
"driverID": "1", // Convert to String
"passengerID":
box.read(BoxName.pasengerID).toString(), // Convert to String
"rideID": "222", // Convert to String
"note": cancelNote
};
print(rideConfirm);
print(payload);
if (rideConfirm == false) {
clearPlaces();
@@ -134,7 +129,13 @@ class MapController extends GetxController {
data = [];
changeCancelRidePageShow();
await CRUD().post(link: AppLink.addCancelRide, payload: payload);
await CRUD().post(link: AppLink.addCancelRide, payload: {
"driverID": "1", // Convert to String
"passengerID":
box.read(BoxName.pasengerID).toString(), // Convert to String
"rideID": "222", // Convert to String
"note": cancelNote
});
update();
}
@@ -244,7 +245,7 @@ class MapController extends GetxController {
}
// Configure location accuracy
LocationAccuracy desiredAccuracy = LocationAccuracy.high;
// LocationAccuracy desiredAccuracy = LocationAccuracy.high;
// Get the current location
LocationData _locationData = await location.getLocation();
@@ -263,6 +264,7 @@ class MapController extends GetxController {
}
Future getCarsLocationByPassenger() async {
carsLocationByPassenger = [];
LatLngBounds bounds =
calculateBounds(mylocation.latitude, mylocation.longitude, 10);
print(
@@ -277,15 +279,29 @@ class MapController extends GetxController {
'northeastLat': northeast.latitude.toString(),
'northeastLon': northeast.longitude.toString(),
});
var data = jsonDecode(res);
// print(data);
for (var i = 0; i < data.length; i++) {
carsLocationByPassenger.add(LatLng(
double.parse(data['message'][i]['latitude']),
double.parse(data['message'][i]['longitude'])));
}
if (res == 'failure') {
Get.defaultDialog(
title: 'No Car in your site.Sorry!',
middleText: '',
confirm: MyElevatedButton(
title: 'Back',
onPressed: () {
Get.back();
markerReloadingTimer.cancel();
}));
} else {
dataCarsLocationByPassenger = jsonDecode(res);
// print(dataCarsLocationByPassenger);
update();
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();
}
}
LatLngBounds calculateBounds(
@@ -315,6 +331,120 @@ class MapController extends GetxController {
update();
}
// void startMarkerReloading() {
// markerReloadingTimer = Timer.periodic(const Duration(seconds: 30), (timer) {
// print('timer==============================');
// reloadMarkers();
// });
// }
late Timer markerReloadingTimer2;
late Timer markerReloadingTimer1;
late int duration1;
void startMarkerReloading() {
// Schedule timer 1 to reload markers at a specific time
DateTime scheduledTime1 = DateTime.now().add(const Duration(seconds: 30));
markerReloadingTimer1 =
Timer(scheduledTime1.difference(DateTime.now()), () {
print('timer 1 ==============================');
reloadMarkers();
});
// Schedule timer 2 to reload markers at a specific time
DateTime scheduledTime2 = DateTime.now().add(const Duration(seconds: 60));
markerReloadingTimer2 =
Timer(scheduledTime2.difference(DateTime.now()), () {
print('timer 2 ==============================');
reloadMarkers();
});
}
void reloadMarkers() async {
await getCarsLocationByPassenger();
// Clear existing markers
markers.clear();
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 the map with the new markers
mapController?.animateCamera(CameraUpdate.newLatLng(
LatLng(mylocation.latitude, mylocation.longitude)));
}
String duratioByPassenger = '';
void getNearestDriverByPassengerLocation() async {
double nearestDistance = double.infinity;
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']),
// );
// }
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=${AppCredintials.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'];
duration1 = data['rows'][0]['elements'][0]['duration']['value'];
duratioByPassenger = data['rows'][0]['elements'][0]['duration']['text'];
if (distance1 < nearestDistance) {
nearestDistance = distance1.toDouble();
nearestCar = CarLocation(
distance: distance1.toDouble(),
duration: duration1.toDouble(),
id: carLocation['driver_id'],
latitude: double.parse(carLocation['latitude']),
longitude: double.parse(carLocation['longitude']),
);
update();
}
}
// Handle the distance and duration as needed
else {
print(
'Failed to retrieve distance and duration: ${response['status']}');
// Handle the failure case
}
}
print(nearestCar!.distance);
print(nearestCar!.duration);
print(nearestCar!.latitude);
print(nearestCar!.longitude);
print(nearestCar!.id);
}
late LatLngBounds boundsData;
getMap(String origin, destination) async {
var origin1 = fromString(origin);
var destination1 = fromString(destination);
@@ -322,13 +452,15 @@ class MapController extends GetxController {
mydestination = destination1;
mylocation = origin1;
update();
await getCarsLocationByPassenger();
// print(carsLocationByPassenger);
var url =
('${AppLink.googleMapsLink}directions/json?&language=en&avoid=tolls|ferries&destination=$destination&origin=$origin&key=${AppCredintials.mapAPIKEY}');
var response = await CRUD().getGoogleApi(link: url, payload: {});
data = response['routes'][0]['legs'];
print(data);
final points =
decodePolyline(response["routes"][0]["overview_polyline"]["points"]);
for (int i = 0; i < points.length; i++) {
@@ -345,8 +477,7 @@ class MapController extends GetxController {
LatLng(bounds['southwest']['lat'], bounds['southwest']['lng']);
// Create the LatLngBounds object
LatLngBounds boundsData =
LatLngBounds(northeast: northeast, southwest: southwest);
boundsData = LatLngBounds(northeast: northeast, southwest: southwest);
// Calculate the zoom level based on the distance and screen size
@@ -376,10 +507,19 @@ class MapController extends GetxController {
);
polylines.add(polyline);
rideConfirm = false;
update();
}
}
showBottomSheet1() async {
bottomSheet();
isButtomSheetShown = true;
heightButtomSheetShown = 250;
update();
}
double getDistanceFromText(String distanceText) {
// Remove any non-digit characters from the distance text
String distanceValue = distanceText.replaceAll(RegExp(r'[^0-9.]+'), '');
@@ -406,6 +546,8 @@ class MapController extends GetxController {
if (data.isNotEmpty) {
String distanceText = await data[0]['distance']['text'];
String durationText = await data[0]['duration']['text'];
print(data[0]['duration']['text']);
print('=================================');
distance = getDistanceFromText(distanceText);
duration = getDistanceFromText(durationText);
durationToAdd = Duration(minutes: duration.toInt());
@@ -562,14 +704,29 @@ class MapController extends GetxController {
@override
void onInit() async {
// getPolyLine();
// getMap();
FirebasMessagesController().requestPermission();
await getLocation();
await getCarsLocationByPassenger();
getNearestDriverByPassengerLocation();
addCustomPicker();
addCustomCarIcon();
startMarkerReloading();
super.onInit();
}
}
class CarLocation {
final int id;
final double latitude;
final double longitude;
double distance;
double duration;
CarLocation({
required this.id,
required this.latitude,
required this.longitude,
this.distance = 10000,
this.duration = 10000,
});
}