### Get and Store Current Location in Firestore Source: https://context7.com/amanullahgit/live-location-tracker-flutter/llms.txt Captures the device's current GPS coordinates using the `location` package and saves them to a Firestore collection named 'location'. Includes a fallback for potential errors during location retrieval. ```dart final loc.Location location = loc.Location(); _getLocation() async { try { final loc.LocationData _locationResult = await location.getLocation(); await FirebaseFirestore.instance.collection('location').doc('user1').set({ 'latitude': _locationResult.latitude, 'longitude': _locationResult.longitude, 'name': 'john' }, SetOptions(merge: true)); } catch (e) { print(e); } } // Firestore document structure: // collection: 'location' // document: 'user1' // { // "latitude": 37.7749, // "longitude": -122.4194, // "name": "john" // } ``` -------------------------------- ### Initialize Firebase and Flutter App Source: https://context7.com/amanullahgit/live-location-tracker-flutter/llms.txt Sets up the main entry point for the Flutter application, ensuring Flutter is initialized, Firebase is configured, and the main application widget is launched. ```dart import 'dart:async'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/material.dart'; import 'package:location/location.dart' as loc; import 'package:permission_handler/permission_handler'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); runApp(MaterialApp(home: MyApp())); } ``` -------------------------------- ### Declare Core Dependencies in pubspec.yaml Source: https://context7.com/amanullahgit/live-location-tracker-flutter/llms.txt Lists the essential Flutter packages required for the live location tracker application, including map integration, location services, Firebase, and permission handling. ```yaml dependencies: flutter: sdk: flutter google_maps_flutter: ^2.3.0 location: ^4.4.0 cloud_firestore: ^4.8.1 firebase_core: ^2.14.0 permission_handler: ^10.3.0 ``` -------------------------------- ### Android Manifest Configuration (XML) Source: https://context7.com/amanullahgit/live-location-tracker-flutter/llms.txt Configures the Android manifest file to include necessary permissions for location access and internet usage, as well as setting up the Google Maps API key. This is crucial for the Flutter application to function correctly on Android devices. Ensure you replace 'YOUR_GOOGLE_MAPS_API_KEY' with your actual key. ```xml ``` -------------------------------- ### Handle Location Permissions in Flutter Source: https://context7.com/amanullahgit/live-location-tracker-flutter/llms.txt Manages user location permissions using the `permission_handler` package. It requests permission, handles granted and denied states, and provides a fallback to open app settings if permissions are permanently denied. ```dart _requestPermission() async { var status = await Permission.location.request(); if (status.isGranted) { print('Location permission granted'); } else if (status.isDenied) { // Recursively request permission _requestPermission(); } else if (status.isPermanentlyDenied) { // Open device settings for manual permission grant openAppSettings(); } } ``` -------------------------------- ### Google Map Display Widget (Dart) Source: https://context7.com/amanullahgit/live-location-tracker-flutter/llms.txt Displays a user's location on Google Maps with live camera updates based on coordinates from Firebase. It uses StreamBuilder to listen for changes in Firestore and updates the map marker and camera position accordingly. Requires google_maps_flutter and Firebase Firestore packages. ```dart // lib/mymap.dart import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; class MyMap extends StatefulWidget { final String user_id; MyMap(this.user_id); @override _MyMapState createState() => _MyMapState(); } class _MyMapState extends State { late GoogleMapController _controller; bool _added = false; @override Widget build(BuildContext context) { return Scaffold( body: StreamBuilder( stream: FirebaseFirestore.instance.collection('location').snapshots(), builder: (context, AsyncSnapshot snapshot) { if (_added) { mymap(snapshot); } if (!snapshot.hasData) { return Center(child: CircularProgressIndicator()); } return GoogleMap( mapType: MapType.normal, markers: { Marker( position: LatLng( snapshot.data!.docs.singleWhere( (element) => element.id == widget.user_id)['latitude'], snapshot.data!.docs.singleWhere( (element) => element.id == widget.user_id)['longitude'], ), markerId: MarkerId('id'), icon: BitmapDescriptor.defaultMarkerWithHue( BitmapDescriptor.hueMagenta), ), }, initialCameraPosition: CameraPosition( target: LatLng( snapshot.data!.docs.singleWhere( (element) => element.id == widget.user_id)['latitude'], snapshot.data!.docs.singleWhere( (element) => element.id == widget.user_id)['longitude'], ), zoom: 14.47, ), onMapCreated: (GoogleMapController controller) async { setState(() { _controller = controller; _added = true; }); }, ); }, ), ); } Future mymap(AsyncSnapshot snapshot) async { await _controller.animateCamera( CameraUpdate.newCameraPosition( CameraPosition( target: LatLng( snapshot.data!.docs.singleWhere( (element) => element.id == widget.user_id)['latitude'], snapshot.data!.docs.singleWhere( (element) => element.id == widget.user_id)['longitude'], ), zoom: 14.47, ), ), ); } } ``` -------------------------------- ### Display Location List from Firebase (Dart) Source: https://context7.com/amanullahgit/live-location-tracker-flutter/llms.txt Streams tracked locations from Firestore and displays them in a scrollable list. Each list item shows the location's name, latitude, and longitude, with an option to navigate to a map view for that specific location. Requires Firebase Firestore and Flutter's material.dart. ```dart StreamBuilder( stream: FirebaseFirestore.instance.collection('location').snapshots(), builder: (context, AsyncSnapshot snapshot) { if (!snapshot.hasData) { return Center(child: CircularProgressIndicator()); } return ListView.builder( itemCount: snapshot.data?.docs.length, itemBuilder: (context, index) { return ListTile( title: Text(snapshot.data!.docs[index]['name'].toString()), subtitle: Row( children: [ Text(snapshot.data!.docs[index]['latitude'].toString()), SizedBox(width: 20), Text(snapshot.data!.docs[index]['longitude'].toString()), ], ), trailing: IconButton( icon: Icon(Icons.directions), onPressed: () { Navigator.of(context).push(MaterialPageRoute( builder: (context) => MyMap(snapshot.data!.docs[index].id) )); }, ), ); } ); }, ) ``` -------------------------------- ### Stream Live Location Updates to Firebase Source: https://context7.com/amanullahgit/live-location-tracker-flutter/llms.txt Subscribes to continuous location changes from the device and pushes each new GPS coordinate to Firestore in real-time. Handles potential errors during the stream and allows for cancellation. ```dart StreamSubscription? _locationSubscription; Future _listenLocation() async { _locationSubscription = location.onLocationChanged.handleError((onError) { print(onError); _locationSubscription?.cancel(); setState(() { _locationSubscription = null; }); }).listen((loc.LocationData currentlocation) async { await FirebaseFirestore.instance.collection('location').doc('user1').set({ 'latitude': currentlocation.latitude, 'longitude': currentlocation.longitude, 'name': 'john' }, SetOptions(merge: true)); }); } // Optional: Configure location settings for background tracking // location.changeSettings(interval: 300, accuracy: loc.LocationAccuracy.high); // location.enableBackgroundMode(enable: true); ``` -------------------------------- ### Stop Live Location Tracking Stream Source: https://context7.com/amanullahgit/live-location-tracker-flutter/llms.txt Provides a function to cancel the ongoing location update stream subscription, effectively stopping real-time location tracking and cleaning up associated resources. ```dart _stopListening() { _locationSubscription?.cancel(); setState(() { _locationSubscription = null; }); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.