Files
runvisionpro_app/lib/screens/google_map_screen.dart

249 lines
13 KiB
Dart

import 'dart:async';
import 'dart:math';
import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:geolocator/geolocator.dart';
import '../constants/app_colors.dart';
class GoogleMapScreen extends StatefulWidget {
const GoogleMapScreen({super.key});
@override
State<GoogleMapScreen> createState() => _GoogleMapScreenState();
}
class _GoogleMapScreenState extends State<GoogleMapScreen> {
GoogleMapController? _mapController;
StreamSubscription<Position>? _positionStreamSubscription;
Timer? _simulationTimer;
final List<LatLng> _routePoints = [];
final Set<Polyline> _polylines = {};
final Set<Marker> _markers = {};
LatLng? _plannedStart;
LatLng? _plannedEnd;
bool _isPlanningMode = false;
double _currentSpeed = 0.0;
double _totalDistance = 0.0;
LatLng _currentPosition = const LatLng(38.7223, -9.1393);
bool _isLoading = true;
bool _isSimulating = false;
BitmapDescriptor? _startIcon;
BitmapDescriptor? _arrowIcon;
BitmapDescriptor? _finishIcon;
@override
void initState() {
super.initState();
_setupIconsAndTracking();
}
Future<void> _setupIconsAndTracking() async {
_startIcon = await _createPremiumMarker(Colors.greenAccent, Icons.play_arrow_rounded, 85);
_finishIcon = await _createPremiumMarker(AppColors.coral, Icons.flag_rounded, 85);
_arrowIcon = await _createArrowMarker(Colors.black, Colors.white, 95);
await _initTracking();
}
Future<BitmapDescriptor> _createPremiumMarker(Color color, IconData icon, double size) async {
final ui.PictureRecorder recorder = ui.PictureRecorder();
final Canvas canvas = Canvas(recorder);
final Paint shadowPaint = Paint()..color = Colors.black.withOpacity(0.4)..maskFilter = const MaskFilter.blur(BlurStyle.normal, 6);
canvas.drawCircle(Offset(size / 2, size / 2 + 3), size / 2, shadowPaint);
canvas.drawCircle(Offset(size / 2, size / 2), size / 2, Paint()..color = Colors.white);
canvas.drawCircle(Offset(size / 2, size / 2), size / 2 - 5, Paint()..color = color);
TextPainter textPainter = TextPainter(textDirection: TextDirection.ltr);
textPainter.text = TextSpan(text: String.fromCharCode(icon.codePoint), style: TextStyle(fontSize: size * 0.6, fontFamily: icon.fontFamily, color: Colors.white, fontWeight: FontWeight.bold));
textPainter.layout();
textPainter.paint(canvas, Offset((size - textPainter.width) / 2, (size - textPainter.height) / 2));
final ui.Image image = await recorder.endRecording().toImage(size.toInt(), size.toInt() + 6);
final ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
return BitmapDescriptor.fromBytes(byteData!.buffer.asUint8List());
}
Future<BitmapDescriptor> _createArrowMarker(Color color, Color borderColor, double size) async {
final ui.PictureRecorder recorder = ui.PictureRecorder();
final Canvas canvas = Canvas(recorder);
final Path path = Path();
path.moveTo(size / 2, 0);
path.lineTo(size * 0.9, size);
path.lineTo(size / 2, size * 0.7);
path.lineTo(size * 0.1, size);
path.close();
canvas.drawPath(path.shift(const Offset(0, 4)), Paint()..color = Colors.black38..maskFilter = const MaskFilter.blur(BlurStyle.normal, 4));
canvas.drawPath(path, Paint()..color = color);
canvas.drawPath(path, Paint()..color = borderColor..style = ui.PaintingStyle.stroke..strokeWidth = 7);
final ui.Image image = await recorder.endRecording().toImage(size.toInt(), size.toInt() + 6);
final ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
return BitmapDescriptor.fromBytes(byteData!.buffer.asUint8List());
}
@override
void dispose() {
_positionStreamSubscription?.cancel();
_simulationTimer?.cancel();
super.dispose();
}
Future<void> _initTracking() async {
bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) return;
LocationPermission permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) return;
}
Position position = await Geolocator.getCurrentPosition();
_currentPosition = LatLng(position.latitude, position.longitude);
setState(() => _isLoading = false);
_startLocationStream();
}
void _startLocationStream() {
_positionStreamSubscription = Geolocator.getPositionStream(locationSettings: const LocationSettings(accuracy: LocationAccuracy.high, distanceFilter: 5)).listen((Position position) {
if (!_isSimulating) _updatePosition(LatLng(position.latitude, position.longitude), position.speed);
});
}
void _updatePosition(LatLng newPoint, double speed) {
setState(() {
if (_routePoints.isNotEmpty) {
_totalDistance += Geolocator.distanceBetween(_currentPosition.latitude, _currentPosition.longitude, newPoint.latitude, newPoint.longitude);
}
_currentSpeed = speed;
_routePoints.add(newPoint);
_currentPosition = newPoint;
// Update only the dynamic follower arrow
_markers.removeWhere((m) => m.markerId.value == 'follower');
_markers.add(Marker(
markerId: const MarkerId('follower'),
position: _currentPosition,
rotation: _calculateRotation(_routePoints),
flat: true,
anchor: const Offset(0.5, 0.5),
icon: _arrowIcon ?? BitmapDescriptor.defaultMarker,
zIndex: 12,
));
if (_routePoints.length > 1) {
_polylines.removeWhere((p) => p.polylineId.value == 'route' || p.polylineId.value == 'route_glow');
_polylines.add(Polyline(
polylineId: const PolylineId('route_glow'),
points: List.from(_routePoints),
color: Colors.lightBlueAccent.withOpacity(0.3),
width: 14,
zIndex: 9,
));
_polylines.add(Polyline(
polylineId: const PolylineId('route'),
points: List.from(_routePoints),
color: Colors.white,
width: 6,
patterns: [PatternItem.dot, PatternItem.gap(15)],
jointType: JointType.round,
zIndex: 10,
));
}
});
_mapController?.animateCamera(CameraUpdate.newLatLng(newPoint));
}
double _calculateRotation(List<LatLng> points) {
if (points.length < 2) return 0;
LatLng p1 = points[points.length - 2];
LatLng p2 = points.last;
return Geolocator.bearingBetween(p1.latitude, p1.longitude, p2.latitude, p2.longitude);
}
void _onMapTap(LatLng point) {
if (!_isPlanningMode) return;
setState(() {
if (_plannedStart == null) {
_plannedStart = point;
_markers.add(Marker(markerId: const MarkerId('planned_start'), position: point, icon: _startIcon ?? BitmapDescriptor.defaultMarker, zIndex: 5));
} else if (_plannedEnd == null) {
_plannedEnd = point;
_markers.add(Marker(markerId: const MarkerId('planned_end'), position: point, icon: _finishIcon ?? BitmapDescriptor.defaultMarker, zIndex: 5));
_polylines.add(Polyline(polylineId: const PolylineId('planned_route'), points: [_plannedStart!, _plannedEnd!], color: Colors.white.withOpacity(0.1), width: 2, zIndex: 1));
} else {
_plannedStart = point;
_plannedEnd = null;
_markers.removeWhere((m) => m.markerId.value.startsWith('planned'));
_polylines.removeWhere((p) => p.polylineId.value == 'planned_route');
_markers.add(Marker(markerId: const MarkerId('planned_start'), position: point, icon: _startIcon ?? BitmapDescriptor.defaultMarker, zIndex: 5));
}
});
}
void _toggleSimulation() {
if (_isSimulating) {
_simulationTimer?.cancel();
setState(() => _isSimulating = false);
} else {
setState(() {
_isSimulating = true;
_isPlanningMode = false;
_routePoints.clear();
_polylines.removeWhere((p) => p.polylineId.value == 'route' || p.polylineId.value == 'route_glow');
_totalDistance = 0.0;
// Start from planned start OR current real location
_currentPosition = _plannedStart ?? _currentPosition;
// Initialize routePoints with the start so the arrow appears immediately at the start point
_routePoints.add(_currentPosition);
// Update only the follower arrow. Planned markers are already in the set.
_markers.removeWhere((m) => m.markerId.value == 'follower');
_markers.add(Marker(
markerId: const MarkerId('follower'),
position: _currentPosition,
flat: true,
anchor: const Offset(0.5, 0.5),
icon: _arrowIcon ?? BitmapDescriptor.defaultMarker,
zIndex: 12,
));
});
_simulationTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
double latStep = 0.00025;
double lngStep = 0.00025;
if (_plannedEnd != null) {
double dist = Geolocator.distanceBetween(_currentPosition.latitude, _currentPosition.longitude, _plannedEnd!.latitude, _plannedEnd!.longitude);
if (dist < 12) {
_updatePosition(_plannedEnd!, 0.0);
_toggleSimulation();
return;
}
latStep = (_plannedEnd!.latitude - _currentPosition.latitude) / (max(dist / 8, 1));
lngStep = (_plannedEnd!.longitude - _currentPosition.longitude) / (max(dist / 8, 1));
}
LatLng nextPoint = LatLng(_currentPosition.latitude + latStep, _currentPosition.longitude + lngStep);
_updatePosition(nextPoint, 3.5 + Random().nextDouble());
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: AppColors.background,
appBar: AppBar(title: Text(_isPlanningMode ? 'PLANEJAR ROTA' : 'CORRIDA VIVA', style: const TextStyle(fontWeight: FontWeight.w900, color: Colors.white, letterSpacing: 2)), centerTitle: true, backgroundColor: Colors.transparent, elevation: 0, leading: IconButton(icon: const Icon(Icons.arrow_back_ios_new, color: Colors.white), onPressed: () => Navigator.pop(context)), actions: [IconButton(icon: Icon(_isPlanningMode ? Icons.check_circle_rounded : Icons.add_location_alt_rounded, color: AppColors.coral, size: 30), onPressed: () => setState(() => _isPlanningMode = !_isPlanningMode))]),
extendBodyBehindAppBar: true,
body: Stack(children: [Center(child: Container(width: MediaQuery.of(context).size.width * 0.94, height: MediaQuery.of(context).size.height * 0.7, decoration: BoxDecoration(color: AppColors.backgroundGrey, borderRadius: BorderRadius.circular(55), border: Border.all(color: Colors.white.withOpacity(0.1), width: 3), boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.7), blurRadius: 50, offset: const Offset(0, 30))]), child: ClipRRect(borderRadius: BorderRadius.circular(52), child: _isLoading ? const Center(child: CircularProgressIndicator(color: AppColors.coral)) : GoogleMap(initialCameraPosition: CameraPosition(target: _currentPosition, zoom: 17.5), onMapCreated: (controller) => _mapController = controller, onTap: _onMapTap, markers: _markers, polylines: _polylines, zoomControlsEnabled: false, myLocationButtonEnabled: false, compassEnabled: false, mapToolbarEnabled: false)))), Positioned(top: 115, left: 45, right: 45, child: Container(padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 25), decoration: BoxDecoration(color: AppColors.background.withOpacity(0.95), borderRadius: BorderRadius.circular(25), border: Border.all(color: Colors.white10), boxShadow: [BoxShadow(color: Colors.black26, blurRadius: 10)]), child: Row(mainAxisAlignment: MainAxisAlignment.spaceAround, children: [_buildStat("RITMO", "${(_currentSpeed * 3.6).toStringAsFixed(1)}", "KM/H"), Container(width: 1, height: 35, color: Colors.white10), _buildStat("TRAJETO", (_totalDistance / 1000).toStringAsFixed(2), "KM")]))), if (_isPlanningMode) Positioned(bottom: 140, left: 60, right: 60, child: Container(padding: const EdgeInsets.all(12), decoration: BoxDecoration(color: Colors.black.withOpacity(0.85), borderRadius: BorderRadius.circular(20), border: Border.all(color: AppColors.coral.withOpacity(0.5))), child: const Text("Toque para definir Início e Fim", textAlign: TextAlign.center, style: TextStyle(color: Colors.white, fontSize: 13, fontWeight: FontWeight.bold))))]),
floatingActionButton: FloatingActionButton.extended(onPressed: _toggleSimulation, label: Text(_isSimulating ? "PARAR" : "INICIAR CORRIDA", style: const TextStyle(fontWeight: FontWeight.w900, letterSpacing: 1.5)), icon: Icon(_isSimulating ? Icons.stop_rounded : Icons.play_arrow_rounded, size: 32), backgroundColor: _isSimulating ? AppColors.coral : Colors.white, foregroundColor: _isSimulating ? Colors.white : AppColors.background, elevation: 15),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
);
}
Widget _buildStat(String label, String value, String unit) {
return Column(mainAxisSize: MainAxisSize.min, children: [Text(label, style: const TextStyle(color: Colors.white54, fontSize: 10, fontWeight: FontWeight.w900, letterSpacing: 1.5)), const SizedBox(height: 6), Row(crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, children: [Text(value, style: const TextStyle(color: Colors.white, fontSize: 26, fontWeight: FontWeight.w900)), const SizedBox(width: 3), Text(unit, style: const TextStyle(color: Colors.white54, fontSize: 10, fontWeight: FontWeight.bold))])]);
}
}