import 'dart:developer'; import 'package:flutter/material.dart'; import 'package:flutter_animate/flutter_animate.dart'; import 'package:geocoding/geocoding.dart'; import 'package:geolocator/geolocator.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'package:prosappco/components/general_primary_button.dart'; class ProfessionalMapScreen extends StatefulWidget { const ProfessionalMapScreen({super.key}); @override State createState() => _ProfessionalMapScreenState(); } class _ProfessionalMapScreenState extends State { final TextEditingController _addressController = TextEditingController(); bool _locationPermissionGranted = false; late GoogleMapController googleMapController; late Position currentPosition; var coords; @override void initState() { super.initState(); _getLocation(); } Future _getLocation() async { try { final position = await _determinePosition(); setState(() { currentPosition = position; _locationPermissionGranted = true; }); } catch (e) { log('Error getting location: $e'); } } Future _determinePosition() async { bool serviceEnabled; LocationPermission permission; serviceEnabled = await Geolocator.isLocationServiceEnabled(); if (!serviceEnabled) { throw 'Location services are disabled'; } permission = await Geolocator.checkPermission(); if (permission == LocationPermission.denied) { permission = await Geolocator.requestPermission(); if (permission == LocationPermission.denied) { throw 'Location permission denied'; } } if (permission == LocationPermission.deniedForever) { throw 'Location permissions are permanently denied'; } return await Geolocator.getCurrentPosition(); } Future getLocationName(double latitude, double longitude) async { String address; List placemarks = await placemarkFromCoordinates(latitude, longitude); Placemark place = placemarks[0]; if (place.thoroughfare != '' || place.subThoroughfare != '') { address = "${place.thoroughfare} ${place.subThoroughfare} ${place.subLocality}, ${place.locality}, ${place.administrativeArea}"; } else { address = ''; } return address; } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Ubicación'), actions: [ IconButton( icon: const Icon(Icons.my_location), onPressed: () async { try { final position = await _determinePosition(); if (googleMapController != null) { googleMapController.animateCamera( CameraUpdate.newCameraPosition( CameraPosition( target: LatLng(position.latitude, position.longitude), zoom: 18, ), ), ); } else { log('Google Map Controller is not initialized.'); } setState(() { currentPosition = position; _locationPermissionGranted = true; }); } catch (e) { log('Error getting location: $e'); setState(() { _locationPermissionGranted = false; }); ScaffoldMessenger.of(context).clearSnackBars(); ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: const Text( 'Los servicios de ubicación están desactivados'), action: SnackBarAction( label: 'Configuración', onPressed: () { Geolocator.openLocationSettings(); }, ), ), ); } }, ), ], ), backgroundColor: const Color(0xFFD6F4FF), body: Stack( children: [ _locationPermissionGranted ? GoogleMap( mapType: MapType.normal, initialCameraPosition: CameraPosition( target: LatLng( currentPosition.latitude, currentPosition.longitude), zoom: 16, ), zoomControlsEnabled: false, myLocationEnabled: true, onMapCreated: (GoogleMapController controller) { googleMapController = controller; }, onCameraMove: (position) { setState(() { coords = position.target; }); }, onCameraIdle: () async { final isLocationEnabled = await Geolocator.isLocationServiceEnabled(); if (!isLocationEnabled) { setState(() { _locationPermissionGranted = false; }); ScaffoldMessenger.of(context).clearSnackBars(); ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: const Text( 'Los servicios de ubicación están desactivados'), action: SnackBarAction( label: 'Configuración', onPressed: () { Geolocator.openLocationSettings(); }, ), ), ); } if (coords != null) { getLocationName(coords.latitude, coords.longitude) .then((locationName) { setState(() { _addressController.text = locationName; }); }); } }, ) : Container( color: Colors.white, child: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ const CircularProgressIndicator() .animate() .fadeOut(duration: const Duration(seconds: 2)), const SizedBox(height: 8), const Text('Cargando...') .animate() .fadeOut(duration: const Duration(seconds: 2)), const Text('Permita los permisos de ubicación') .animate() .fadeIn(delay: const Duration(seconds: 2)) .scale(), ], ), ), ), _locationPermissionGranted ? Container( decoration: BoxDecoration( color: Colors.white, boxShadow: [ BoxShadow( color: Colors.grey.withOpacity(0.5), spreadRadius: 1, blurRadius: 5, offset: const Offset(0, 2), ), ], ), child: Padding( padding: const EdgeInsets.only( left: 18, right: 18, bottom: 15, ), child: TextFormField( readOnly: true, controller: _addressController, decoration: const InputDecoration( prefixIcon: Icon(Icons.near_me), hintText: 'Dirección', ), ), ), ) : const SizedBox(), _locationPermissionGranted ? const Positioned( bottom: 30, right: 0, left: 0, top: 0, child: Icon( Icons.location_on, size: 40, color: Colors.red, ), ) : const SizedBox(), _locationPermissionGranted ? Positioned( bottom: 30, child: SizedBox( width: MediaQuery.of(context).size.width, child: Center( child: GeneralPrimaryButton( label: 'Guardar', isEnabled: _locationPermissionGranted, onPressed: () { Navigator.pop(context, { "address": _addressController.text, 'latitude': coords.latitude, 'longitude': coords.longitude, }); }, ), ), ), ) : const SizedBox(), ], ), ); } }