import 'dart:convert'; import 'dart:typed_data'; import 'dart:io'; import 'package:flutter/services.dart'; // For loading assets import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; import 'package:mapbox_gl/mapbox_gl.dart'; import 'package:flutter_dotenv/flutter_dotenv.dart'; // Import dotenv import '../classes/alert.dart'; // Assuming this contains your error dialog code. import '../classes/events.dart'; // Your Event class, assuming you are using it. import '../variable/globals.dart' as globals; import 'package:shared_preferences/shared_preferences.dart'; void main() async { await dotenv.load(fileName: ".env"); // Load .env file runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: const Mapboxpages(title: 'Event Location', place: "Flutter"), ); } } class Mapboxpages extends StatefulWidget { const Mapboxpages({Key? key, required this.title, required this.place}) : super(key: key); final String title; final String place; @override State createState() => _MapboxpagesState(); } class _MapboxpagesState extends State with ShowErrorDialog { late String mapboxAccessToken; late MapboxMapController mapController; // Mark mapController as nullable double longitude = 0.0; double latitude = 0.0; bool isLoading = true; @override void initState() { super.initState(); _initToken(); _getEventInfo(); } // Load the Mapbox access token from the .env file void _initToken() { mapboxAccessToken = dotenv.env['MAPBOX_ACCESS_TOKEN'] ?? ''; if (mapboxAccessToken.isEmpty) { showErrorDialog(context, "Mapbox Access Token is not available."); return; } } Future _getEventInfo() async { SharedPreferences prefs = await SharedPreferences.getInstance(); var accessToken = prefs.getString("access_token") ?? ""; if (accessToken.isNotEmpty) { var urlGet = Uri.parse("${globals.api}/events/${widget.title}"); var responseGet = await http.get(urlGet, headers: {HttpHeaders.cookieHeader: 'access_token=${accessToken}'}); stderr.writeln('Response Get status: ${responseGet.statusCode}'); if (responseGet.statusCode == 200) { var events = jsonDecode(utf8.decode(responseGet.bodyBytes)); latitude = events["latitude"]; longitude = events["longitude"]; setState(() { isLoading = false; }); } else { 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 { showErrorDialog(context, "Cache invalide"); } } // Load image from assets as Uint8List Future _loadMarkerImage() async { final ByteData data = await rootBundle.load('images/marker.png'); return data.buffer.asUint8List(); } void _onMapCreated(MapboxMapController controller) { mapController = controller; } // Called when the map is created void _onStyleLoaded() async { // Log the map controller and coordinates print("Mapbox controller initialized: $mapController"); print("lat - long : $latitude - $longitude"); // Check if the mapController is really initialized if (mapController != null) { try { // Ensure the coordinates are valid if (latitude != 0.0 && longitude != 0.0) { // Load marker image as Uint8List final markerImage = await _loadMarkerImage(); // Register the image with Mapbox await mapController!.addImage("custom-marker", markerImage); final symbolOptions = SymbolOptions( geometry: LatLng(latitude, longitude), iconImage: "custom-marker", // Use the registered custom marker iconSize: 0.5, // Optional: Adjust size ); // Debugging symbol options print("Adding symbol with options: $symbolOptions"); // Add symbol to map mapController!.addSymbol(symbolOptions); } else { print("Error: Invalid coordinates, cannot add symbol."); } } catch (e) { // Handle any exception that occurs when adding the symbol print("Error when adding symbol: $e"); } } else { print( "Error: MapboxMapController is null at the time of symbol addition"); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text(widget.place)), body: isLoading ? Center(child: CircularProgressIndicator()) : MapboxMap( accessToken: mapboxAccessToken, // Your Mapbox API key onMapCreated: _onMapCreated, onStyleLoadedCallback: _onStyleLoaded, initialCameraPosition: CameraPosition( target: LatLng(latitude, longitude), zoom: 14.0, ), ), ); } }