get location from starting app

This commit is contained in:
2024-11-06 13:27:31 +01:00
parent 3a0f24cc4c
commit 5c0f4d345d
9 changed files with 278 additions and 71 deletions

View File

@@ -10,7 +10,9 @@ import 'package:shared_preferences/shared_preferences.dart';
import 'package:intl/intl.dart';
import 'package:intl/date_symbol_data_local.dart';
import 'dart:math';
import 'package:geolocator/geolocator.dart';
import '../variable/globals.dart' as globals;
import 'package:permission_handler/permission_handler.dart';
void main() {
initializeDateFormatting("fr_FR", null).then((_) => runApp(const MyApp()));
@@ -63,8 +65,137 @@ class _MyHomePageState extends State<ListItemMenu> {
@override
void initState() {
super.initState();
_checkLocationPermission();
// Initialize data fetch when the page loads
_fetchInitialData();
_getCurrentLocation();
}
// Check if location permission is granted
Future<void> _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<void> _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<void> _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<void> _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<void> _getCityAndCountry(double latitude, double longitude) async {
await dotenv.load(fileName: ".env"); // Load .env file
final mapboxAccessToken = dotenv.env['MAPBOX_ACCESS_TOKEN'] ?? '';
final url = Uri.parse(
'https://api.mapbox.com/geocoding/v5/mapbox.places/$longitude,$latitude.json?access_token=$mapboxAccessToken',
);
try {
// Send GET request to Mapbox API
final response = await http.get(url);
// If the request is successful (HTTP status 200)
print("status mapbox : ${response.statusCode}");
if (response.statusCode == 200) {
// Parse the response body
final data = json.decode(response.body);
// Extract the city and country from the response
final features = data['features'];
if (features.isNotEmpty) {
String city = _getCityFromFeatures(features);
String country = _getCountryFromFeatures(features);
print("city : ${city} ${country}");
if (city.isNotEmpty && country.isNotEmpty) {
setState(() {
inputGeo.text = "${city}, ${country}";
});
fetchPostsByLocation(latitude, longitude);
} else {
_fetchInitialData();
}
} else {
_fetchInitialData();
}
} else {
_fetchInitialData();
throw Exception('Failed to load location data');
}
} catch (e) {
print("Error getting city and country: $e");
_fetchInitialData();
}
}
// Helper function to extract the city from the Mapbox features array
String _getCityFromFeatures(List<dynamic> features) {
for (var feature in features) {
if (feature['place_type'] != null &&
feature['place_type'].contains('place')) {
return feature['text'] ?? '';
}
}
return '';
}
// Helper function to extract the country from the Mapbox features array
String _getCountryFromFeatures(List<dynamic> features) {
for (var feature in features) {
if (feature['place_type'] != null &&
feature['place_type'].contains('country')) {
return feature['text'] ?? '';
}
}
return '';
}
// Fetch initial data from API or any other necessary initialization