get lati long from backend

This commit is contained in:
Valentin CZERYBA 2024-11-15 23:22:17 +01:00
parent 7182e0e324
commit 74e55f3d6b
3 changed files with 72 additions and 37 deletions

View File

@ -5,9 +5,8 @@ class Events {
String? startDate; String? startDate;
String? endDate; String? endDate;
String? description; String? description;
String? zipCode; double? latitude;
String? city; double? longitude;
String? country;
Events({this.place, this.id, this.name, this.startDate}); Events({this.place, this.id, this.name, this.startDate});
@ -18,8 +17,7 @@ class Events {
startDate = json["start_date"]; startDate = json["start_date"];
endDate = json['end_date']; endDate = json['end_date'];
description = json['description']; description = json['description'];
zipCode = json["zip_code"]; latitude = json['latitude'];
city = json['city']; longitude = json['longitude'];
country = json['country'];
} }
} }

View File

@ -16,7 +16,6 @@ import '../variable/globals.dart' as globals;
import '../classes/events.dart'; import '../classes/events.dart';
import 'ListItemMenu.dart'; import 'ListItemMenu.dart';
import 'ListItemByTags.dart';
import 'MapboxPages.dart'; import 'MapboxPages.dart';
import 'ListItemByOrganizers.dart'; import 'ListItemByOrganizers.dart';
@ -245,7 +244,9 @@ class _ItemMenuState extends State<ItemMenu> with ShowErrorDialog {
Navigator.push( Navigator.push(
context, context,
MaterialPageRoute( MaterialPageRoute(
builder: (_) => Mapboxpages(title: '$place'))); builder: (_) => Mapboxpages(
title: '${widget.title}',
place: '${place}')));
}, },
child: Text("${place}", child: Text("${place}",
style: TextStyle(fontSize: 15.0), style: TextStyle(fontSize: 15.0),

View File

@ -11,6 +11,8 @@ import '../classes/alert.dart'; // Assuming this contains your error dialog code
import '../classes/events.dart'; // Your Event class, assuming you are using it. import '../classes/events.dart'; // Your Event class, assuming you are using it.
import '../variable/globals.dart' as globals; import '../variable/globals.dart' as globals;
import 'package:shared_preferences/shared_preferences.dart';
void main() async { void main() async {
await dotenv.load(fileName: ".env"); // Load .env file await dotenv.load(fileName: ".env"); // Load .env file
runApp(const MyApp()); runApp(const MyApp());
@ -26,15 +28,17 @@ class MyApp extends StatelessWidget {
theme: ThemeData( theme: ThemeData(
primarySwatch: Colors.blue, primarySwatch: Colors.blue,
), ),
home: const Mapboxpages(title: 'Event Location'), home: const Mapboxpages(title: 'Event Location', place: "Flutter"),
); );
} }
} }
class Mapboxpages extends StatefulWidget { class Mapboxpages extends StatefulWidget {
const Mapboxpages({Key? key, required this.title}) : super(key: key); const Mapboxpages({Key? key, required this.title, required this.place})
: super(key: key);
final String title; final String title;
final String place;
@override @override
State<Mapboxpages> createState() => _MapboxpagesState(); State<Mapboxpages> createState() => _MapboxpagesState();
@ -51,46 +55,78 @@ class _MapboxpagesState extends State<Mapboxpages> with ShowErrorDialog {
void initState() { void initState() {
super.initState(); super.initState();
_initToken(); _initToken();
_getEventInfo();
} }
// Load the Mapbox access token from the .env file // Load the Mapbox access token from the .env file
void _initToken() async { void _initToken() {
mapboxAccessToken = dotenv.env['MAPBOX_ACCESS_TOKEN'] ?? ''; mapboxAccessToken = dotenv.env['MAPBOX_ACCESS_TOKEN'] ?? '';
if (mapboxAccessToken.isEmpty) { if (mapboxAccessToken.isEmpty) {
showErrorDialog(context, "Mapbox Access Token is not available."); showErrorDialog(context, "Mapbox Access Token is not available.");
return; return;
} }
// Fetch event location using the title (address or name)
await _fetchEventLocation();
} }
// Fetch location coordinates using the event title Future<void> _getEventInfo() async {
Future<void> _fetchEventLocation() async { SharedPreferences prefs = await SharedPreferences.getInstance();
if (widget.title.isNotEmpty && mapboxAccessToken.isNotEmpty) { var accessToken = prefs.getString("access_token") ?? "";
final geocodeUrl = Uri.parse(
'https://api.mapbox.com/geocoding/v5/mapbox.places/${Uri.encodeComponent(widget.title)}.json?access_token=$mapboxAccessToken',
);
final geocodeResponse = await http.get(geocodeUrl); if (accessToken.isNotEmpty) {
var urlGet = Uri.parse("${globals.api}/events/${widget.title}");
if (geocodeResponse.statusCode == 200) { var responseGet = await http.get(urlGet,
final geocodeData = json.decode(geocodeResponse.body); headers: {HttpHeaders.cookieHeader: 'access_token=${accessToken}'});
if (geocodeData['features'].isNotEmpty) { stderr.writeln('Response Get status: ${responseGet.statusCode}');
final coordinates = if (responseGet.statusCode == 200) {
geocodeData['features'][0]['geometry']['coordinates']; var events = jsonDecode(utf8.decode(responseGet.bodyBytes));
print("geodate : ${geocodeData['features'][0]}"); latitude = events["latitude"];
longitude = coordinates[0]; // Longitude longitude = events["longitude"];
latitude = coordinates[1]; // Latitude
setState(() { setState(() {
isLoading = false; isLoading = false;
}); });
} else { } else {
showErrorDialog(context, "Location not found."); var text = "";
switch (responseGet.statusCode) {
case 400:
{
text = "Requête mal construite";
}
break;
case 406:
{
text = "Mot de passe incorrect";
}
break;
case 404:
{
text = "Utilisateur inconnu";
}
break;
case 403:
{
text = "Vous n'avez pas l'autorisation de faire cette action";
}
break;
case 410:
{
text = "Token invalide";
}
break;
case 500:
{
text = "Probleme interne du serveur";
}
break;
default:
{
text = "Probleme d'authentification inconnu";
}
break;
}
showErrorDialog(context, text);
} }
} else { } else {
showErrorDialog(context, "Failed to fetch location data."); showErrorDialog(context, "Cache invalide");
}
} }
} }
@ -148,7 +184,7 @@ class _MapboxpagesState extends State<Mapboxpages> with ShowErrorDialog {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
appBar: AppBar(title: Text(widget.title)), appBar: AppBar(title: Text(widget.place)),
body: isLoading body: isLoading
? Center(child: CircularProgressIndicator()) ? Center(child: CircularProgressIndicator())
: MapboxMap( : MapboxMap(