166 lines
5.1 KiB
Dart
Raw Normal View History

2024-11-11 14:48:23 +01:00
import 'dart:convert';
2024-11-13 23:47:40 +01:00
import 'dart:typed_data';
2024-11-11 14:48:23 +01:00
import 'dart:io';
2024-11-13 23:47:40 +01:00
import 'package:flutter/services.dart'; // For loading assets
2024-11-11 14:48:23 +01:00
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<Mapboxpages> createState() => _MapboxpagesState();
}
class _MapboxpagesState extends State<Mapboxpages> with ShowErrorDialog {
late String mapboxAccessToken;
2024-11-15 22:48:05 +01:00
late MapboxMapController mapController; // Mark mapController as nullable
2024-11-11 14:48:23 +01:00
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<void> _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'];
2024-11-13 23:47:40 +01:00
print("geodate : ${geocodeData['features'][0]}");
2024-11-11 14:48:23 +01:00
longitude = coordinates[0]; // Longitude
latitude = coordinates[1]; // Latitude
setState(() {
isLoading = false;
});
2024-11-13 23:47:40 +01:00
} else {
showErrorDialog(context, "Location not found.");
2024-11-11 14:48:23 +01:00
}
} else {
showErrorDialog(context, "Failed to fetch location data.");
}
}
}
2024-11-13 23:47:40 +01:00
// Load image from assets as Uint8List
Future<Uint8List> _loadMarkerImage() async {
final ByteData data = await rootBundle.load('images/marker.png');
return data.buffer.asUint8List();
}
2024-11-15 22:48:05 +01:00
void _onMapCreated(MapboxMapController controller) {
2024-11-11 14:48:23 +01:00
mapController = controller;
2024-11-15 22:48:05 +01:00
}
2024-11-11 14:48:23 +01:00
2024-11-15 22:48:05 +01:00
// Called when the map is created
void _onStyleLoaded() async {
2024-11-11 14:48:23 +01:00
// 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 {
2024-11-13 23:47:40 +01:00
// 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.");
}
2024-11-11 14:48:23 +01:00
} 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,
2024-11-15 22:48:05 +01:00
onStyleLoadedCallback: _onStyleLoaded,
2024-11-11 14:48:23 +01:00
initialCameraPosition: CameraPosition(
target: LatLng(latitude, longitude),
zoom: 14.0,
),
),
);
}
}