From b22458021b709cda1fb2c376ff64a4cda51375ed Mon Sep 17 00:00:00 2001 From: Valentin CZERYBA Date: Wed, 6 Nov 2024 15:55:15 +0100 Subject: [PATCH] get events from current position --- covas_mobile/lib/main.dart | 40 ++++++++ covas_mobile/lib/pages/ListItemMenu.dart | 123 ++++++++++++----------- 2 files changed, 107 insertions(+), 56 deletions(-) diff --git a/covas_mobile/lib/main.dart b/covas_mobile/lib/main.dart index 1db7c0d..be4b083 100644 --- a/covas_mobile/lib/main.dart +++ b/covas_mobile/lib/main.dart @@ -11,6 +11,7 @@ import 'pages/ListItemMenu.dart'; import 'classes/alert.dart'; import 'variable/globals.dart' as globals; +import 'package:permission_handler/permission_handler.dart'; void main() { runApp(MyApp()); @@ -153,10 +154,49 @@ class _LoginDemoState extends State with ShowErrorDialog { @override void initState() { + _checkLocationPermission(); start(); super.initState(); } + Future _checkLocationPermission() async { + PermissionStatus status = await Permission.location.status; + + if (status.isGranted) { + print("Location permission granted"); + } else if (status.isDenied) { + print("Location permission denied"); + _requestLocationPermission(); + } else if (status.isPermanentlyDenied) { + print("Location permission permanently denied"); + openAppSettings(); + } + } + + // Request location permission + Future _requestLocationPermission() async { + PermissionStatus status = await Permission.location.request(); + + if (status.isGranted) { + print("Location permission granted"); + } else if (status.isDenied) { + print("Location permission denied"); + } else if (status.isPermanentlyDenied) { + print("Location permission permanently denied"); + openAppSettings(); + } + } + + // Open app settings to allow user to grant permission manually + Future _openAppSettings() async { + bool opened = await openAppSettings(); + if (opened) { + print("App settings opened"); + } else { + print("Failed to open app settings"); + } + } + @override Widget build(BuildContext context) { return Scaffold( diff --git a/covas_mobile/lib/pages/ListItemMenu.dart b/covas_mobile/lib/pages/ListItemMenu.dart index 1a83313..bde1c0f 100644 --- a/covas_mobile/lib/pages/ListItemMenu.dart +++ b/covas_mobile/lib/pages/ListItemMenu.dart @@ -47,6 +47,52 @@ class _MyHomePageState extends State { // Fetching events from API static Future> getPosts() async { + PermissionStatus status = await Permission.location.status; + var url = Uri.parse("${globals.api}/events"); + if (status.isGranted) { + print("Location permission granted"); + + // Get the current position with high accuracy + LocationSettings locationSettings = LocationSettings( + accuracy: LocationAccuracy.high, + distanceFilter: + 10, // Optional: Minimum distance (in meters) to trigger location update + ); + + Position position = await Geolocator.getCurrentPosition( + locationSettings: locationSettings, + ); + // Calculate the boundaries + double radiusInKm = 50; + double latDistance = radiusInKm / 111.0; + double lonDistance = + radiusInKm / (111.0 * cos(position.latitude * pi / 180)); + + double minLat = position.latitude - latDistance; + double maxLat = position.latitude + latDistance; + double minLon = position.longitude - lonDistance; + double maxLon = position.longitude + lonDistance; + + url = Uri.parse("${globals.api}/events/search" + "?min_lat=$minLat&max_lat=$maxLat" + "&min_lon=$minLon&max_lon=$maxLon"); + } + SharedPreferences prefs = await SharedPreferences.getInstance(); + var accessToken = prefs.getString("access_token") ?? ""; + final List body = []; + if (accessToken.isNotEmpty) { + final response = await http.get(url, headers: { + "Content-Type": "application/json", + HttpHeaders.cookieHeader: "access_token=${accessToken}" + }); + final List body = json.decode(utf8.decode(response.bodyBytes)); + return body.map((e) => Events.fromJson(e)).toList(); + } + return body; + } + + // Fetching events from API + Future> getAllPosts() async { SharedPreferences prefs = await SharedPreferences.getInstance(); var accessToken = prefs.getString("access_token") ?? ""; final List body = []; @@ -65,70 +111,34 @@ class _MyHomePageState extends State { @override void initState() { super.initState(); - _checkLocationPermission(); // Initialize data fetch when the page loads _getCurrentLocation(); } - // Check if location permission is granted - Future _checkLocationPermission() async { + // Get the device's current location + Future _getCurrentLocation() async { PermissionStatus status = await Permission.location.status; if (status.isGranted) { print("Location permission granted"); - } else if (status.isDenied) { - print("Location permission denied"); - _requestLocationPermission(); - } else if (status.isPermanentlyDenied) { - print("Location permission permanently denied"); - openAppSettings(); + + // Get the current position with high accuracy + LocationSettings locationSettings = LocationSettings( + accuracy: LocationAccuracy.high, + distanceFilter: + 10, // Optional: Minimum distance (in meters) to trigger location update + ); + + Position position = await Geolocator.getCurrentPosition( + locationSettings: locationSettings, + ); + + // Reverse geocode: Get city and country from latitude and longitude using Mapbox Search API + final place = + await _getCityAndCountry(position.latitude, position.longitude); } } - // Request location permission - Future _requestLocationPermission() async { - PermissionStatus status = await Permission.location.request(); - - if (status.isGranted) { - print("Location permission granted"); - } else if (status.isDenied) { - print("Location permission denied"); - _fetchInitialData(); - } else if (status.isPermanentlyDenied) { - print("Location permission permanently denied"); - openAppSettings(); - } - } - - // Open app settings to allow user to grant permission manually - Future _openAppSettings() async { - bool opened = await openAppSettings(); - if (opened) { - print("App settings opened"); - } else { - print("Failed to open app settings"); - _fetchInitialData(); - } - } - - // Get the device's current location - Future _getCurrentLocation() async { - // Get the current position with high accuracy - LocationSettings locationSettings = LocationSettings( - accuracy: LocationAccuracy.high, - distanceFilter: - 10, // Optional: Minimum distance (in meters) to trigger location update - ); - - Position position = await Geolocator.getCurrentPosition( - locationSettings: locationSettings, - ); - - // Reverse geocode: Get city and country from latitude and longitude using Mapbox Search API - final place = - await _getCityAndCountry(position.latitude, position.longitude); - } - // Method to get city and country from latitude and longitude using Mapbox API Future _getCityAndCountry(double latitude, double longitude) async { await dotenv.load(fileName: ".env"); // Load .env file @@ -156,10 +166,10 @@ class _MyHomePageState extends State { String country = _getCountryFromFeatures(features); print("city : ${city} ${country}"); if (city.isNotEmpty && country.isNotEmpty) { + fetchPostsByLocation(latitude, longitude); setState(() { inputGeo.text = "${city}, ${country}"; }); - fetchPostsByLocation(latitude, longitude); } else { _fetchInitialData(); } @@ -171,8 +181,8 @@ class _MyHomePageState extends State { throw Exception('Failed to load location data'); } } catch (e) { - print("Error getting city and country: $e"); _fetchInitialData(); + print("Error getting city and country: $e"); } } @@ -202,7 +212,7 @@ class _MyHomePageState extends State { Future _fetchInitialData() async { try { // Optionally, you can fetch posts initially if needed. - List initialPosts = await getPosts(); + List initialPosts = await getAllPosts(); setState(() { // Assign to the postsFuture and update the filtered posts if needed filteredPosts = initialPosts; @@ -392,6 +402,7 @@ class _MyHomePageState extends State { // Function to display fetched data on screen Widget buildPosts(List posts) { + print("posts : ${posts}"); print("filteredposts : ${filteredPosts}"); final displayedPosts = filteredPosts; print("results ${displayedPosts}");