Files
tripz/lib/controller/home/map_page_controller.dart
Hamza-Ayed 6a3865a3d1 8-18/1
2023-08-18 22:59:16 +03:00

516 lines
16 KiB
Dart

import 'dart:convert';
import 'dart:math' show sqrt, pi, cos, sin;
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:google_polyline_algorithm/google_polyline_algorithm.dart';
import 'package:location/location.dart';
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:ride/views/home/map_widget.dart/buttom_sheet_map_show.dart';
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;
TextEditingController placeController = TextEditingController();
List data = [];
List<LatLng> bounds = [];
List places = [];
LatLngBounds? boundsdata;
List<Marker> markers = [];
List<Polyline> polylines = [];
late LatLng mylocation;
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 = [];
BitmapDescriptor markerIcon = BitmapDescriptor.defaultMarker;
BitmapDescriptor carIcon = BitmapDescriptor.defaultMarker;
double height = 150;
final location = Location();
late LocationData currentLocation;
double heightMenu = 0;
double heightPickerContainer = 90;
double mainBottomMenuMap = Get.height * .2;
bool heightMenuBool = false;
bool isPickerShown = false;
bool isButtomSheetShown = false;
bool mapType = false;
bool isCancelRidePageShown = false;
bool isCashConfirmPageShown = false;
bool isPaymentMethodPageShown = false;
bool isMainBottomMenuMap = true;
double heightButtomSheetShown = 300;
double cashConfirmPageShown = 250;
double paymentPageShown = 380;
late final LatLng southwest;
late final LatLng northeast;
List<CarLocationModel> carLocations = <CarLocationModel>[];
// final mainBottomMenuMap = GlobalKey<AnimatedContainer>();
void changeButtomSheetShown() {
isButtomSheetShown = !isButtomSheetShown;
heightButtomSheetShown = isButtomSheetShown == true ? 250 : 0;
update();
}
void changeCashConfirmPageShown() {
isCashConfirmPageShown = !isCashConfirmPageShown;
cashConfirmPageShown = isCashConfirmPageShown == true ? 250 : 0;
update();
}
void changePaymentMethodPageShown() {
isPaymentMethodPageShown = !isPaymentMethodPageShown;
paymentPageShown = isPaymentMethodPageShown == true ? Get.height * .6 : 0;
update();
}
void changeMapType() {
mapType = !mapType;
// heightButtomSheetShown = isButtomSheetShown == true ? 240 : 0;
update();
}
void changeCancelRidePageShow() {
// rideConfirm == true
// ?
isCancelRidePageShown = !isCancelRidePageShown;
// : cancelRide();
update();
}
void getDrawerMenu() {
heightMenuBool = !heightMenuBool;
heightMenu = heightMenuBool == true ? 100 : 0;
update();
}
void clearPlaces() {
places = [];
update();
}
int selectedReason = -1;
void selectReason(int index) {
selectedReason = index;
update();
}
bool rideConfirm = false;
void cancelRide() async {
if (rideConfirm == false) {
clearPlaces();
clearpolyline();
data = [];
changeCancelRidePageShow();
update();
} else {
clearPlaces();
clearpolyline();
data = [];
changeCancelRidePageShow();
await CRUD().post(link: AppLink.addCancelRide, payload: {
"driverID": 1,
"passengerID": box.read(BoxName.pasengerID).toString(),
"rideID": 222,
"note": "zxcz"
});
update();
}
}
void changePickerShown() {
isPickerShown = !isPickerShown;
heightPickerContainer = isPickerShown == true ? 150 : 90;
update();
}
void changeMainBottomMenuMap() {
isMainBottomMenuMap = !isMainBottomMenuMap;
mainBottomMenuMap =
isMainBottomMenuMap == true ? Get.height * .2 : Get.height * .66;
update();
}
changeHeight() {
if (places.isEmpty) {
height = 0;
update();
}
height = 150;
update();
}
hidePlaces() {
height = 0;
update();
}
Future getPlaces() async {
var url =
// '${AppLink.googleMapsLink}place/nearbysearch/json?location=${mylocation.longitude}&radius=25000&language=ar&keyword=&key=${placeController.text}${AppCredintials.mapAPIKEY}';
'${AppLink.googleMapsLink}place/nearbysearch/json?keyword=${placeController.text}&location=${mylocation.latitude},${mylocation.longitude}&radius=50000&language=ar&key=${AppCredintials.mapAPIKEY}';
var response = await CRUD().getGoogleApi(link: url, payload: {});
places = response['results'];
print(places);
update();
}
LatLng fromString(String location) {
List<String> parts = location.split(',');
double lat = double.parse(parts[0]);
double lng = double.parse(parts[1]);
return LatLng(lat, lng);
}
void clearpolyline() {
polylines = [];
polylineCoordinates.clear();
update();
}
void addCustomPicker() {
ImageConfiguration config = const ImageConfiguration(
size: Size(20, 20),
// scale: 1.0,
);
BitmapDescriptor.fromAssetImage(config, 'assets/images/picker.png')
.then((value) {
markerIcon = value;
update();
});
}
void addCustomCarIcon() {
ImageConfiguration config = const ImageConfiguration(
size: Size(50, 50),
// scale: 1.0,
);
BitmapDescriptor.fromAssetImage(config, 'assets/images/car.png')
.then((value) {
carIcon = value;
update();
});
}
Future<void> getLocation() async {
isloading = true;
update();
bool serviceEnabled;
PermissionStatus permissionGranted;
// Check if location services are enabled
serviceEnabled = await location.serviceEnabled();
if (!serviceEnabled) {
serviceEnabled = await location.requestService();
if (!serviceEnabled) {
// Location services are still not enabled, handle the error
return;
}
}
// Check if the app has permission to access location
permissionGranted = await location.hasPermission();
if (permissionGranted == PermissionStatus.denied) {
permissionGranted = await location.requestPermission();
if (permissionGranted != PermissionStatus.granted) {
// Location permission is still not granted, handle the error
return;
}
}
// Configure location accuracy
LocationAccuracy desiredAccuracy = LocationAccuracy.high;
// Get the current location
LocationData _locationData = await location.getLocation();
mylocation =
(_locationData.latitude != null && _locationData.longitude != null
? LatLng(_locationData.latitude!, _locationData.longitude!)
: null)!;
// Print location details
print('Accuracy: ${_locationData.accuracy}');
print('Latitude: ${_locationData.latitude}');
print('Longitude: ${_locationData.longitude}');
print('Time: ${_locationData.time}');
isloading = false;
update();
}
Future getCarsLocationByPassenger() async {
LatLngBounds bounds =
calculateBounds(mylocation.latitude, mylocation.longitude, 10);
print(
'Southwest: ${bounds.southwest.latitude}, ${bounds.southwest.longitude}');
print(
'Northeast: ${bounds.northeast.latitude}, ${bounds.northeast.longitude}');
var res =
await CRUD().get(link: AppLink.getCarsLocationByPassenger, payload: {
'southwestLat': southwest.latitude.toString(),
'southwestLon': southwest.longitude.toString(),
'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'])));
}
update();
}
LatLngBounds calculateBounds(
double centerLat, double centerLng, double radius) {
double radius = 2000; // 10 km in meters
southwest = LatLng(
centerLat - (radius / 111000),
centerLng - (radius / (111000 * cos(centerLat))),
);
northeast = LatLng(
centerLat + (radius / 111000),
centerLng + (radius / (111000 * cos(centerLat))),
);
return LatLngBounds(southwest: southwest, northeast: northeast);
}
GoogleMapController? mapController;
void onMapCreated(GoogleMapController controller) {
mapController = controller;
controller.getVisibleRegion();
controller.animateCamera(
CameraUpdate.newLatLng(mylocation),
);
update();
}
getMap(String origin, destination) async {
var origin1 = fromString(origin);
var destination1 = fromString(destination);
isloading = false;
mydestination = destination1;
mylocation = origin1;
update();
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'];
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();
polylineCoordinates.add(LatLng(lat, lng));
}
// Define the northeast and southwest coordinates
final bounds = response["routes"][0]["bounds"];
LatLng northeast =
LatLng(bounds['northeast']['lat'], bounds['northeast']['lng']);
LatLng southwest =
LatLng(bounds['southwest']['lat'], bounds['southwest']['lng']);
// Create the LatLngBounds object
LatLngBounds boundsData =
LatLngBounds(northeast: northeast, southwest: southwest);
// Calculate the zoom level based on the distance and screen size
double distanceOfDestnation =
getDistanceFromText(data[0]['distance']['text']);
// Animate the camera to the adjusted bounds
if (distanceOfDestnation <= 10) {
mapController!.animateCamera(CameraUpdate.newLatLngZoom(mylocation, 14));
} else if (distanceOfDestnation > 10 && distanceOfDestnation < 16) {
mapController!.animateCamera(CameraUpdate.newLatLngZoom(mylocation, 12));
} else if (distanceOfDestnation > 16 && distanceOfDestnation < 30) {
mapController!.animateCamera(CameraUpdate.newLatLngZoom(mylocation, 10));
} else if (distanceOfDestnation > 30 && distanceOfDestnation < 100) {
mapController!.animateCamera(CameraUpdate.newLatLngZoom(mylocation, 8));
} else if (distanceOfDestnation > 100) {
mapController!.animateCamera(CameraUpdate.newLatLngZoom(mylocation, 6));
}
if (polylines.isNotEmpty) {
clearpolyline();
} else {
var polyline = Polyline(
polylineId: PolylineId(response["routes"][0]["summary"]),
points: polylineCoordinates,
width: 10,
color: Colors.blue,
);
polylines.add(polyline);
update();
}
}
double getDistanceFromText(String distanceText) {
// Remove any non-digit characters from the distance text
String distanceValue = distanceText.replaceAll(RegExp(r'[^0-9.]+'), '');
// Parse the extracted numerical value as a double
double distance = double.parse(distanceValue);
return distance;
}
late double totaME;
late double tax;
late double totalPassenger;
late double totalDriver;
late double averageDuration;
late double costDuration;
late double cost;
late double distance;
late double duration;
DateTime currentTime = DateTime.now();
late Duration durationToAdd;
late DateTime newTime;
void bottomSheet() {
if (data.isNotEmpty) {
String distanceText = data[0]['distance']['text'];
String durationText = data[0]['duration']['text'];
distance = getDistanceFromText(distanceText);
duration = getDistanceFromText(durationText);
durationToAdd = Duration(minutes: duration.toInt());
newTime = currentTime.add(durationToAdd);
if (distanceText.contains('km')) {
cost = distance * 0.21;
} else {
cost = distance * 0.21 / 1000;
}
averageDuration = duration / distance;
costDuration = duration * averageDuration * 0.016;
totalDriver = cost + costDuration;
totalPassenger = totalDriver + (totalDriver * .16);
tax = totalPassenger * .04;
totaME = totalPassenger - totalDriver - tax;
if (totalPassenger < 1) {
totalPassenger = 1;
if (totalDriver < .5) {
totalDriver = .85;
totaME = .11;
} else {
totalDriver = .95;
totaME = .05;
}
}
}
buttomSheetMapPage();
// Get.bottomSheet(
// Container(
// height: 130,
// decoration: const BoxDecoration(
// color: AppColor.secondaryColor,
// borderRadius: BorderRadius.only(
// topLeft: Radius.circular(15), topRight: Radius.circular(15))),
// child: data.isEmpty
// ? Center(
// child: Text(
// 'Where are you want to go..',
// style: AppStyle.title,
// ))
// : Center(
// child: Column(
// children: [
// Row(
// mainAxisAlignment: MainAxisAlignment.spaceAround,
// children: [
// Text(
// 'distance is ${data[0]['distance']['text']}',
// style: AppStyle.title,
// ),
// Text(
// 'duration is ${data[0]['duration']['text']}',
// style: AppStyle.title,
// ),
// ],
// ),
// Row(
// mainAxisAlignment: MainAxisAlignment.spaceAround,
// children: [
// Text(
// 'Cost for .21/km ${cost.toStringAsFixed(2)} ',
// style: AppStyle.title,
// ),
// Text(
// 'costDuration ${averageDuration.toStringAsFixed(2)} is ${costDuration.toStringAsFixed(2)} ',
// style: AppStyle.title,
// ),
// ],
// ),
// Row(
// mainAxisAlignment: MainAxisAlignment.spaceAround,
// children: [
// Text(
// 'Cost for passenger ${totalPassenger.toStringAsFixed(2)} ',
// style: AppStyle.title,
// ),
// Text(
// 'totaME ${totaME.toStringAsFixed(2)} ',
// style: AppStyle.title,
// ),
// ],
// ),
// Text(
// 'totalDriver ${totalDriver.toStringAsFixed(2)}',
// style: AppStyle.title,
// ),
// ],
// ),
// ),
// ),
// elevation: 6,
// enableDrag: true,
// isScrollControlled: true,
// isDismissible: true,
// useRootNavigator: true,
// backgroundColor: Colors.transparent,
// barrierColor: AppColor.accentColor.withOpacity(.4),
// persistent: true,
// shape: ShapeBorder.lerp(
// RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
// RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)),
// 0.5),
// );
}
List<LatLng> polylineCoordinate = [];
@override
void onInit() async {
// getPolyLine();
// getMap();
FirebasMessagesController().requestPermission();
await getLocation();
await getCarsLocationByPassenger();
addCustomPicker();
addCustomCarIcon();
super.onInit();
}
}