Update map_camera.dart

This commit is contained in:
ASHUTOSH AGARWAL
2024-04-18 11:16:41 +05:30
parent d153d259a9
commit 7cfc529e9c

View File

@@ -1,7 +1,7 @@
import 'package:intl/intl.dart'; import 'package:intl/intl.dart';
import 'dart:ui' as ui; import 'dart:ui' as ui;
import 'package:latlong2/latlong.dart' as lat; import 'package:latlong2/latlong.dart' as lat;
import '../../map_camera_flutter.dart'; import 'package:map_camera_flutter/map_camera_flutter.dart';
///import 'package:your_app/map_camera_flutter.dart'; // Import the file where the MapCameraLocation widget is defined ///import 'package:your_app/map_camera_flutter.dart'; // Import the file where the MapCameraLocation widget is defined
@@ -103,19 +103,7 @@ class _MapCameraLocationState extends State<MapCameraLocation> {
/// Represents geocoded location information. /// Represents geocoded location information.
String? latitudeServer; LocationData? locationData;
/// Latitude value of the current location as a string.
String? longitudeServer;
/// Longitude value of the current location as a string.
String? locationName;
/// Name of the current location as a string.
String? subLocation;
/// SubLocation of the current location as a string. /// SubLocation of the current location as a string.
@@ -123,18 +111,18 @@ class _MapCameraLocationState extends State<MapCameraLocation> {
ImageAndLocationData getImageAndLocationData() { ImageAndLocationData getImageAndLocationData() {
return ImageAndLocationData( return ImageAndLocationData(
imagePath: cameraImagePath?.path, imagePath: cameraImagePath?.path,
latitude: latitudeServer, locationData: locationData,
longitude: longitudeServer,
locationName: locationName,
subLocation: subLocation,
); );
} }
Timer? _positionTimer;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
Timer.periodic(const Duration(seconds: 1), (timer) async { _positionTimer = Timer.periodic(const Duration(seconds: 1), (timer) async {
await updatePosition(context); if (mounted) {
await updatePosition(context);
}
}); });
// Initialize the camera controller // Initialize the camera controller
@@ -154,9 +142,24 @@ class _MapCameraLocationState extends State<MapCameraLocation> {
void dispose() { void dispose() {
_controller.dispose(); _controller.dispose();
_followCurrentLocationStreamController.close(); _followCurrentLocationStreamController.close();
_positionTimer?.cancel();
super.dispose(); super.dispose();
} }
@override
void setState(fn) {
if (mounted) {
super.setState(fn);
} else {
WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
if (mounted) {
super.setState(fn);
}
});
}
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
@@ -165,166 +168,171 @@ class _MapCameraLocationState extends State<MapCameraLocation> {
future: _initializeControllerFuture, future: _initializeControllerFuture,
builder: (context, snapshot) { builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) { if (snapshot.connectionState == ConnectionState.done) {
return RepaintBoundary( return Center(
key: globalKey, child: RepaintBoundary(
child: Stack( key: globalKey,
children: [ child: Stack(
CameraPreview( children: [
_controller, CameraPreview(
), _controller,
Positioned( ),
left: 0, Positioned(
right: 0, left: 0,
bottom: 10, right: 0,
child: Column( bottom: 10,
mainAxisAlignment: MainAxisAlignment.center, child: Column(
children: [ mainAxisAlignment: MainAxisAlignment.center,
SizedBox( children: [
height: 160, SizedBox(
child: Row( height: 160,
crossAxisAlignment: CrossAxisAlignment.start, child: Row(
children: [ crossAxisAlignment: CrossAxisAlignment.start,
Padding( children: [
padding: Padding(
const EdgeInsets.symmetric(horizontal: 8.0), padding: const EdgeInsets.symmetric(
child: Card( horizontal: 8.0),
elevation: 3, child: Card(
shape: RoundedRectangleBorder( elevation: 3,
borderRadius: BorderRadius.circular(8.0)), shape: RoundedRectangleBorder(
child: SizedBox( borderRadius:
// height: 130, BorderRadius.circular(8.0)),
width: 120, child: SizedBox(
child: Padding( // height: 130,
padding: const EdgeInsets.all(5.0), width: 120,
child: latitudeServer == null child: Padding(
? const Center( padding: const EdgeInsets.all(5.0),
child: child: locationData == null
CircularProgressIndicator()) ? const Center(
: FlutterMap( child:
options: MapOptions( CircularProgressIndicator())
initialCenter: : FlutterMap(
const lat.LatLng(0, 0), options: MapOptions(
initialZoom: 13.0, initialCenter:
onPositionChanged: const lat.LatLng(0, 0),
(MapPosition position, initialZoom: 13.0,
bool hasGesture) { onPositionChanged:
if (hasGesture) { (MapPosition position,
setState( bool hasGesture) {
() => if (hasGesture) {
_followOnLocationUpdate = setState(
AlignOnUpdate () =>
.never, _followOnLocationUpdate =
); AlignOnUpdate
} .never,
}, );
}
},
),
children: [
TileLayer(
urlTemplate:
'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
userAgentPackageName:
'com.example.app',
minZoom: 12,
),
CurrentLocationLayer(
alignPositionStream:
_followCurrentLocationStreamController
.stream,
alignPositionOnUpdate:
_followOnLocationUpdate,
),
],
), ),
children: [ ),
TileLayer(
urlTemplate:
'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
userAgentPackageName:
'com.example.app',
minZoom: 12,
),
CurrentLocationLayer(
alignPositionStream:
_followCurrentLocationStreamController
.stream,
alignPositionOnUpdate:
_followOnLocationUpdate,
),
],
),
), ),
), ),
), ),
), Expanded(
Expanded( child: Container(
child: Container( padding: const EdgeInsets.all(10),
padding: const EdgeInsets.all(10), decoration: BoxDecoration(
decoration: BoxDecoration( borderRadius: BorderRadius.circular(8),
borderRadius: BorderRadius.circular(8), color: Colors.black.withOpacity(0.5)),
color: Colors.black.withOpacity(0.5)), child: Column(
child: Column( crossAxisAlignment:
crossAxisAlignment: CrossAxisAlignment.start,
CrossAxisAlignment.start, children: [
children: [ Text(
Text( locationData?.locationName ??
locationName ?? "Loading...", "Loading...",
maxLines: 1, maxLines: 1,
overflow: TextOverflow.ellipsis, overflow: TextOverflow.ellipsis,
softWrap: false, softWrap: false,
style: const TextStyle( style: const TextStyle(
color: Colors.white, color: Colors.white,
fontSize: 16, fontSize: 16,
fontWeight: FontWeight.bold), fontWeight: FontWeight.bold),
), ),
const SizedBox( const SizedBox(
height: 5, height: 5,
), ),
Text( Text(
subLocation ?? "Loading ..", locationData?.subLocation ??
maxLines: 2, "Loading ..",
overflow: TextOverflow.ellipsis, maxLines: 2,
softWrap: false, overflow: TextOverflow.ellipsis,
style: const TextStyle( softWrap: false,
color: Colors.white, style: const TextStyle(
fontSize: 12, color: Colors.white,
fontWeight: FontWeight.w500), fontSize: 12,
), fontWeight: FontWeight.w500),
const SizedBox( ),
height: 5, const SizedBox(
), height: 5,
Text( ),
"Lat ${latitudeServer ?? "Loading.."}", Text(
maxLines: 2, "Lat ${locationData?.latitude ?? "Loading.."}",
overflow: TextOverflow.ellipsis, maxLines: 2,
softWrap: false, overflow: TextOverflow.ellipsis,
style: const TextStyle( softWrap: false,
color: Colors.white, style: const TextStyle(
fontSize: 12, color: Colors.white,
fontWeight: FontWeight.w500), fontSize: 12,
), fontWeight: FontWeight.w500),
const SizedBox( ),
height: 5, const SizedBox(
), height: 5,
Text( ),
"Long ${longitudeServer ?? "Loading.."}", Text(
maxLines: 2, "Long ${locationData?.longitude ?? "Loading.."}",
overflow: TextOverflow.ellipsis, maxLines: 2,
softWrap: false, overflow: TextOverflow.ellipsis,
style: const TextStyle( softWrap: false,
color: Colors.white, style: const TextStyle(
fontSize: 12, color: Colors.white,
fontWeight: FontWeight.w500), fontSize: 12,
), fontWeight: FontWeight.w500),
const SizedBox( ),
height: 5, const SizedBox(
), height: 5,
Text( ),
dateTime ?? "Loading...", Text(
maxLines: 2, dateTime ?? "Loading...",
overflow: TextOverflow.ellipsis, maxLines: 2,
softWrap: false, overflow: TextOverflow.ellipsis,
style: const TextStyle( softWrap: false,
color: Colors.white, style: const TextStyle(
fontSize: 12, color: Colors.white,
fontWeight: FontWeight.w500), fontSize: 12,
), fontWeight: FontWeight.w500),
], ),
],
),
), ),
), ),
), const SizedBox(
const SizedBox( width: 10,
width: 10, )
) ],
], ),
), ),
), ],
], ),
), ),
), ],
], ),
), ),
); );
} else { } else {
@@ -386,10 +394,7 @@ class _MapCameraLocationState extends State<MapCameraLocation> {
if (widget.onImageCaptured != null) { if (widget.onImageCaptured != null) {
ImageAndLocationData data = ImageAndLocationData( ImageAndLocationData data = ImageAndLocationData(
imagePath: imgFile.path, imagePath: imgFile.path,
latitude: latitudeServer, locationData: locationData,
longitude: longitudeServer,
locationName: locationName,
subLocation: subLocation,
); );
widget.onImageCaptured!(data); widget.onImageCaptured!(data);
} }
@@ -411,39 +416,43 @@ class _MapCameraLocationState extends State<MapCameraLocation> {
final placeMarks = final placeMarks =
await placemarkFromCoordinates(position.latitude, position.longitude); await placemarkFromCoordinates(position.latitude, position.longitude);
LocationData locationData;
if (placeMarks.isNotEmpty) { if (placeMarks.isNotEmpty) {
final placeMark = placeMarks.first; final placeMark = placeMarks.first;
locationData = LocationData(
latitude: position.latitude.toString(),
longitude: position.longitude.toString(),
locationName:
"${placeMark.locality ?? ""}, ${placeMark.administrativeArea ?? ""}, ${placeMark.country ?? ""}",
subLocation:
"${placeMark.street ?? ""}, ${placeMark.thoroughfare ?? ""} ${placeMark.administrativeArea ?? ""}");
} else {
locationData = LocationData(
longitude: null,
latitude: null,
locationName: 'No Location Data',
subLocation: "");
}
if (locationData != this.locationData) {
// Update the state variables with the retrieved location data // Update the state variables with the retrieved location data
setState(() { setState(() {
latitudeServer = position.latitude.toString(); this.locationData = locationData;
longitudeServer = position.longitude.toString();
locationName =
"${placeMark.locality ?? ""}, ${placeMark.administrativeArea ?? ""}, ${placeMark.country ?? ""}";
subLocation =
"${placeMark.street ?? ""}, ${placeMark.thoroughfare ?? ""} ${placeMark.administrativeArea ?? ""}";
}); });
}
if (kDebugMode) { if (kDebugMode) {
print( print(
"Latitude: $latitudeServer, Longitude: $longitudeServer, Location: $locationName"); "Latitude: ${locationData.latitude}, Longitude: ${locationData.longitude}, Location: ${locationData.locationName}");
}
} else {
// Handle case when no placeMark is available
setState(() {
latitudeServer = null;
longitudeServer = null;
locationName = 'No Location Data';
subLocation = '';
});
} }
} catch (e) { } catch (e) {
// Handle any errors that occurred during location retrieval // Handle any errors that occurred during location retrieval
setState(() { setState(() {
latitudeServer = null; locationData = LocationData(
longitudeServer = null; longitude: null,
locationName = 'Error Retrieving Location'; latitude: null,
subLocation = ''; locationName: 'Error Retrieving Location',
subLocation: "");
}); });
} }
} }