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; 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'), ); } } class Mapboxpages extends StatefulWidget { const Mapboxpages({Key? key, required this.title}) : super(key: key); final String title; @override State createState() => _MapboxpagesState(); } class _MapboxpagesState extends State with ShowErrorDialog { late String mapboxAccessToken; MapboxMapController? mapController; // Mark mapController as nullable double longitude = 0.0; double latitude = 0.0; bool isLoading = true; @override void initState() { super.initState(); _initToken(); } // Load the Mapbox access token from the .env file void _initToken() async { mapboxAccessToken = dotenv.env['MAPBOX_ACCESS_TOKEN'] ?? ''; if (mapboxAccessToken.isEmpty) { showErrorDialog(context, "Mapbox Access Token is not available."); return; } // Fetch event location using the title (address or name) await _fetchEventLocation(); } // Fetch location coordinates using the event title Future _fetchEventLocation() async { if (widget.title.isNotEmpty && mapboxAccessToken.isNotEmpty) { 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 (geocodeResponse.statusCode == 200) { final geocodeData = json.decode(geocodeResponse.body); if (geocodeData['features'].isNotEmpty) { final coordinates = geocodeData['features'][0]['geometry']['coordinates']; print("geodate : ${geocodeData['features'][0]}"); longitude = coordinates[0]; // Longitude latitude = coordinates[1]; // Latitude setState(() { isLoading = false; }); } else { showErrorDialog(context, "Location not found."); } } else { showErrorDialog(context, "Failed to fetch location data."); } } } // Load image from assets as Uint8List Future _loadMarkerImage() async { final ByteData data = await rootBundle.load('images/marker.png'); return data.buffer.asUint8List(); } // Called when the map is created void _onMapCreated(MapboxMapController controller) async { mapController = controller; // 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.title)), body: isLoading ? Center(child: CircularProgressIndicator()) : MapboxMap( accessToken: mapboxAccessToken, // Your Mapbox API key onMapCreated: _onMapCreated, initialCameraPosition: CameraPosition( target: LatLng(latitude, longitude), zoom: 14.0, ), ), ); } }