Files
driver_tripz/lib/controller/functions/location_controller.dart
Hamza-Ayed d23020188e 8/27/1
2024-08-27 10:49:43 +03:00

236 lines
8.5 KiB
Dart

import 'dart:async';
import 'package:SEFER/controller/home/captin/home_captain_controller.dart';
import 'package:get/get.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:location/location.dart';
import 'package:SEFER/constant/box_name.dart';
import 'package:SEFER/constant/links.dart';
import 'package:SEFER/controller/functions/crud.dart';
import 'package:SEFER/controller/home/payment/captain_wallet_controller.dart';
import 'package:SEFER/main.dart';
import '../../print.dart';
// LocationController.dart
class LocationController extends GetxController {
LocationData? _currentLocation;
late Location location;
bool isLoading = false;
late double heading = 0;
late double accuracy = 0;
late double previousTime = 0;
late double latitude;
late double totalDistance = 0;
late double longitude;
late DateTime time;
late double speed = 0;
late double speedAccuracy = 0;
late double headingAccuracy = 0;
bool isActive = false;
late LatLng myLocation;
String totalPoints = '0';
LocationData? get currentLocation => _currentLocation;
Timer? _locationTimer;
@override
void onInit() async {
super.onInit();
location = Location();
getLocation();
// startLocationUpdates();
totalPoints = Get.put(CaptainWalletController()).totalPoints.toString();
// isActive = Get.put(HomeCaptainController()).isActive;
} // Function to determine which area the coordinates belong to
String getLocationArea(double latitude, double longitude) {
// Giza Boundary Check
if (latitude >= 29.904975 &&
latitude <= 30.143372 &&
longitude >= 30.787030 &&
longitude <= 31.238843) {
// box.write(BoxName.serverChosen, AppLink.seferGizaServer);
return 'Giza';
}
// Cairo Boundary Check
else if (latitude >= 29.918901 &&
latitude <= 30.198857 &&
longitude >= 31.215009 &&
longitude <= 31.532186) {
// box.write(BoxName.serverChosen, AppLink.seferCairoServer);
return 'Cairo';
}
// Alexandria Boundary Check
else if (latitude >= 30.396286 &&
latitude <= 31.654458 &&
longitude >= 29.041139 &&
longitude <= 32.626259) {
// box.write(BoxName.serverChosen, AppLink.seferAlexandriaServer);
return 'Alexandria';
}
// Return 'Unknown' if outside defined areas
return 'Unknown';
}
Future<void> startLocationUpdates() async {
if (box.read(BoxName.driverID) != null) {
_locationTimer =
Timer.periodic(const Duration(seconds: 5), (timer) async {
try {
totalPoints =
Get.find<CaptainWalletController>().totalPoints.toString();
isActive = Get.find<HomeCaptainController>().isActive;
if (isActive) {
if (double.parse(totalPoints) > -3000) {
await getLocation();
String endpoint;
switch (
getLocationArea(myLocation.latitude, myLocation.longitude)) {
case 'Cairo':
endpoint = AppLink.addCarsLocationCairoEndpoint;
break;
case 'Giza':
endpoint = AppLink.addCarsLocationGizaEndpoint;
break;
case 'Alexandria':
endpoint = AppLink.addCarsLocationAlexandriaEndpoint;
break;
default:
print('Location outside Cairo, Giza, or Alexandria');
endpoint = AppLink.addCarsLocationByPassenger;
return;
}
if (box.read(BoxName.driverID) != null) {
await CRUD().post(link: endpoint, payload: {
'driver_id': box.read(BoxName.driverID).toString(),
'latitude': myLocation.latitude.toString(),
'longitude': myLocation.longitude.toString(),
'heading': heading.toString(),
'speed': (speed * 3.6).toStringAsFixed(1),
'distance': totalDistance == 0
? '0.0'
: totalDistance < 1
? totalDistance.toStringAsFixed(3)
: totalDistance.toStringAsFixed(1),
'status': box.read(BoxName.statusDriverLocation).toString()
});
// Animate camera to user location (optional)
// if (Get.find<HomeCaptainController>().rideId == 'rideId') {
// Get.find<MapDriverController>()
// .mapController!
// .animateCamera(CameraUpdate.newLatLng(LatLng(
// Get.find<LocationController>().myLocation.latitude,
// Get.find<LocationController>().myLocation.longitude,
// )));
}
Get.find<HomeCaptainController>()
.mapHomeCaptainController!
.animateCamera(CameraUpdate.newLatLng(LatLng(
Get.find<LocationController>().myLocation.latitude,
Get.find<LocationController>().myLocation.longitude,
)));
// if (Get.find<HomeCaptainController>().rideId == '0') {
// await sql.insertData({
// 'driver_id': box.read(BoxName.driverID),
// 'latitude': myLocation.latitude.toString(),
// 'longitude': myLocation.longitude.toString(),
// 'created_at': DateTime.now().toString(),
// }, TableName.carLocations);
// } else {
// await sql.insertData({
// 'order_id': Get.find<MapDriverController>().rideId,
// 'created_at': DateTime.now().toString(),
// 'lat': myLocation.latitude.toString(),
// 'lng': myLocation.longitude.toString(),
// }, TableName.rideLocation);
// }
}
//
}
// }
} catch (e) {
// Handle the error gracefully
}
});
}
}
void stopLocationUpdates() {
_locationTimer?.cancel();
}
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)!;
getLocationArea(_locationData.latitude!, _locationData.longitude!);
speed = _locationData.speed!;
heading = _locationData.heading!;
// Calculate the distance between the current location and the previous location
if (Get.find<HomeCaptainController>().rideId == 'rideId') {
Log.print(
'Get.find<HomeCaptainController>().rideId: ${Get.find<HomeCaptainController>().rideId}');
if (previousTime > 0) {
double distance = calculateDistanceInKmPerHour(
previousTime, _locationData.time, speed);
totalDistance += distance;
}
previousTime = _locationData.time!;
}
// Print location details
// isLoading = false;
update();
}
double calculateDistanceInKmPerHour(
double? startTime, double? endTime, double speedInMetersPerSecond) {
// Calculate the time difference in hours
double timeDifferenceInHours = (endTime! - startTime!) / 1000 / 3600;
// Convert speed to kilometers per hour
double speedInKmPerHour = speedInMetersPerSecond * 3.6;
// Calculate the distance in kilometers
double distanceInKilometers = speedInKmPerHour * timeDifferenceInHours;
return distanceInKilometers;
}
}