### Install geoflutterfire_plus Source: https://pub.dev/packages/geoflutterfire_plus Commands to add the package to a Flutter project. ```bash flutter pub add geoflutterfire_plus ``` ```yaml dependencies: geoflutterfire_plus: ``` -------------------------------- ### Example State Management Source: https://pub.dev/packages/geoflutterfire_plus/example Manages the state for the example page, including the set of markers displayed on the map and the current geographic query conditions. ```dart class ExampleState extends State { /// [Marker]s on Google Maps. Set _markers = {}; /// [BehaviorSubject] of currently geo query radius and camera position. final _geoQueryCondition = BehaviorSubject<_GeoQueryCondition>.seeded( _GeoQueryCondition( radiusInKm: _initialRadiusInKm, cameraPosition: _initialCameraPosition, ), ); /// [Stream] of geo query result. late final Stream>>> _stream = _geoQueryCondition.switchMap( (geoQueryCondition) => GeoCollectionReference(_collectionReference).subscribeWithin( center: GeoFirePoint( GeoPoint( _cameraPosition.target.latitude, _cameraPosition.target.longitude, ), ), radiusInKm: geoQueryCondition.radiusInKm, field: 'geo', geopointFrom: (data) => (data['geo'] as Map)['geopoint'] as GeoPoint, strictMode: true, ), ); /// Updates [_markers] by fetched geo [DocumentSnapshot]s. void _updateMarkersByDocumentSnapshots( List>> documentSnapshots, ) { final markers = {}; for (final ds in documentSnapshots) { final id = ds.id; final data = ds.data(); if (data == null) { continue; } final name = data['name'] as String; final geoPoint = (data['geo'] as Map)['geopoint'] as GeoPoint; markers.add(_createMarker(id: id, name: name, geoPoint: geoPoint)); } debugPrint('📍 markers count: ${markers.length}'); setState(() { _markers = markers; }); } /// Creates a [Marker] by fetched geo location. Marker _createMarker({ required String id, required String name, required GeoPoint geoPoint, }) => Marker( markerId: MarkerId('(${geoPoint.latitude}, ${geoPoint.longitude})'), position: LatLng(geoPoint.latitude, geoPoint.longitude), infoWindow: InfoWindow(title: name), onTap: () => showDialog( context: context, builder: (context) => SetOrDeleteLocationDialog( id: id, name: name, geoFirePoint: GeoFirePoint( GeoPoint(geoPoint.latitude, geoPoint.longitude), ), ), ), ); /// Current detecting radius in kilometers. double get _radiusInKm => _geoQueryCondition.value.radiusInKm; /// Current camera position on Google Maps. CameraPosition get _cameraPosition => _geoQueryCondition.value.cameraPosition; /// Initial geo query detection radius in km. static const double _initialRadiusInKm = 1; /// Google Maps initial camera zoom level. ``` -------------------------------- ### App Widget Setup Source: https://pub.dev/packages/geoflutterfire_plus/example Configures the root MaterialApp widget for the Flutter application, setting up the theme and the initial home screen. ```dart class App extends StatelessWidget { const App({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', debugShowCheckedModeBanner: false, theme: ThemeData( sliderTheme: SliderThemeData( overlayShape: SliderComponentShape.noOverlay, ), ), home: const Example(), // See using with converter example by removing comment below: // home: const WithConverterExample(), // See adding custom queries example by removing comment below: // home: const AdditionalQueryExample(), // home: const GeoFlutterFire2Example(), ); } } ``` -------------------------------- ### Import geoflutterfire_plus in Dart Source: https://pub.dev/packages/geoflutterfire_plus/install Import the geoflutterfire_plus library into your Dart files to start using its functionalities. ```dart import 'package:geoflutterfire_plus/geoflutterfire_plus.dart'; ``` -------------------------------- ### Initialize GoogleMap with GeoFlutterFire Plus Source: https://pub.dev/packages/geoflutterfire_plus/example Configures the initial state of the GoogleMap widget, including camera position and event listeners for map interactions. The `onMapCreated` callback starts listening to a stream for document snapshot updates. ```dart GoogleMap( zoomControlsEnabled: false, myLocationButtonEnabled: false, initialCameraPosition: _initialCameraPosition, onMapCreated: (_) => _stream.listen(_updateMarkersByDocumentSnapshots), markers: _markers, circles: { Circle( circleId: const CircleId('value'), center: LatLng( _cameraPosition.target.latitude, _cameraPosition.target.longitude, ), // multiple 1000 to convert from kilometers to meters. radius: _radiusInKm * 1000, fillColor: Colors.black12, strokeWidth: 0, ), }, onCameraMove: (cameraPosition) { debugPrint('📷 lat: ${cameraPosition.target.latitude}, ' 'lng: ${cameraPosition.target.latitude}'); _geoQueryCondition.add( _GeoQueryCondition( radiusInKm: _radiusInKm, cameraPosition: cameraPosition, ), ); }, onLongPress: (latLng) => showDialog( context: context, builder: (context) => AddLocationDialog(latLng: latLng), ), ) ``` -------------------------------- ### Add geoflutterfire_plus to pubspec.yaml Source: https://pub.dev/packages/geoflutterfire_plus/install This is an example of how the geoflutterfire_plus dependency will appear in your pubspec.yaml file after running `flutter pub add`. ```yaml dependencies: geoflutterfire_plus: ^0.0.34 ``` -------------------------------- ### Firestore Collection and Geopoint Extraction Source: https://pub.dev/packages/geoflutterfire_plus Get a reference to your Firestore collection and define a function to extract GeoPoint data from documents. ```dart // Reference to locations collection. final CollectionReference> collectionReference = FirebaseFirestore.instance.collection('locations'); // Function to get GeoPoint instance from Cloud Firestore document data. GeoPoint geopointFrom(Map data) => (data['geo'] as Map)['geopoint'] as GeoPoint; ``` -------------------------------- ### Initialize Firebase and Run App Source: https://pub.dev/packages/geoflutterfire_plus/example Sets up Firebase initialization and runs the main application widget. Ensure Firebase is initialized before running the app. ```dart void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform); runApp(const App()); } ``` -------------------------------- ### Define package prerequisites Source: https://pub.dev/packages/geoflutterfire_plus Minimum Dart and Flutter SDK versions required for the package. ```text Dart: '>=2.17.0 <3.0.0' Flutter: '>=2.10.0' ``` -------------------------------- ### Perform Basic Geo-Query Source: https://pub.dev/packages/geoflutterfire_plus Subscribe to a stream of document snapshots within a specified radius from the center point. ```dart // Streamed document snapshots of geo query under given conditions. final Stream>>> stream = GeoCollectionReference>(collectionReference) .subscribeWithin( center: center, radiusInKm: radiusInKm, field: field, geopointFrom: geopointFrom, ); ``` -------------------------------- ### Create GeoFirePoint data Source: https://pub.dev/packages/geoflutterfire_plus Instantiate a GeoFirePoint and retrieve the map containing the GeoPoint and Geohash. ```dart // Define GeoFirePoint by instantiating GeoFirePoint with latitude and longitude. final GeoFirePoint geoFirePoint = GeoFirePoint(GeoPoint(35.681236, 139.767125)); // Gets GeoPoint instance and Geohash string as Map. final Map data = geoFirePoint.data; // {geopoint: Instance of 'GeoPoint', geohash: xn76urx66} print(data); ``` -------------------------------- ### Debug Window UI for GeoFlutterFire Plus Source: https://pub.dev/packages/geoflutterfire_plus/example Displays a debug overlay on the map showing the current marker count, radius, and a slider to adjust the search radius. This UI helps in visualizing and interacting with the geo-query parameters. ```dart Container( width: double.infinity, margin: const EdgeInsets.only(top: 64, left: 16, right: 16), padding: const EdgeInsets.all(16), decoration: const BoxDecoration( color: Colors.black38, borderRadius: BorderRadius.all(Radius.circular(8)), ), child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ const Text( 'Debug window', style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold, ), ), const SizedBox(height: 8), Text( 'Currently detected count: ' '${_markers.length}', style: const TextStyle(color: Colors.white), ), const SizedBox(height: 8), Text( 'Current radius: ' '${_radiusInKm.toStringAsFixed(1)} (km)', style: const TextStyle(color: Colors.white), ), const SizedBox(height: 8), Slider( value: _radiusInKm, min: 1, max: 100, divisions: 99, label: _radiusInKm.toStringAsFixed(1), onChanged: (value) => _geoQueryCondition.add( _GeoQueryCondition( radiusInKm: value, cameraPosition: _cameraPosition, ), ), ), ], ), ) ``` -------------------------------- ### Define GeoFirePoint and Query Parameters Source: https://pub.dev/packages/geoflutterfire_plus Set up the center point, radius, and the Firestore field containing geohash data for your geo-query. ```dart // cloud_firestore [GeoPoint] of Tokyo Station. const GeoPoint tokyoStation = GeoPoint(35.681236, 139.767125); // Center of the geo query. final GeoFirePoint center = GeoFirePoint(tokyoStation); // Detection range from the center point. const double radiusInKm = 50; // Field name of Cloud Firestore documents where the geohash is saved. const String field = 'geo'; ``` -------------------------------- ### Add geoflutterfire_plus Dependency Source: https://pub.dev/packages/geoflutterfire_plus/install Use this command to add the geoflutterfire_plus package to your Flutter project. This command automatically updates your pubspec.yaml file. ```bash $ flutter pub add geoflutterfire_plus ``` -------------------------------- ### Perform Type-Safe Geo-Query with Converter Source: https://pub.dev/packages/geoflutterfire_plus Execute a geo-query using the typed collection reference, receiving streams of typed Location document snapshots. ```dart // Streamed typed document snapshots of geo query under given conditions. final Stream>> stream = GeoCollectionReference(typedCollectionReference).subscribeWithin( center: center, radiusInKm: radiusInKm, field: field, geopointFrom: geopointFrom, ); ``` -------------------------------- ### Define Typed Collection Reference with Converter Source: https://pub.dev/packages/geoflutterfire_plus Configure a Firestore collection reference to use a converter for automatic serialization and deserialization of Location objects. ```dart /// Reference to the collection where the location data is stored. final typedCollectionReference = FirebaseFirestore.instance.collection('locations').withConverter( fromFirestore: (ds, _) => Location.fromDocumentSnapshot(ds), toFirestore: (obj, _) => obj.toJson(), ); // Function to get GeoPoint instance from Location instance. GeoPoint geopointFrom: (Location location) => location.geo.geopoint; ``` -------------------------------- ### Geo Query Condition Class Source: https://pub.dev/packages/geoflutterfire_plus/example A simple class to hold the parameters for a geographic query, including the radius and the camera position. ```dart class _GeoQueryCondition { _GeoQueryCondition({ required this.radiusInKm, required this.cameraPosition, }); final double radiusInKm; final CameraPosition cameraPosition; } ``` -------------------------------- ### Define a custom query condition Source: https://pub.dev/packages/geoflutterfire_plus Define a function that takes a Query object and returns a modified Query with additional filters. ```dart // Custom query condition. Query queryBuilder(Query query) => query.where('isVisible', isEqualTo: true); ``` -------------------------------- ### Apply custom query to a geo-query Source: https://pub.dev/packages/geoflutterfire_plus Pass the defined queryBuilder function to the subscribeWithin method to filter results. ```dart // Streamed typed document snapshots of geo query under custom query conditions. final Stream>>> stream = GeoCollectionReference>(typedCollectionReference) .subscribeWithin( center: center, radiusInKm: radiusInKm, field: field, geopointFrom: geopointFrom, // Specify queryBuilder parameter here. queryBuilder: queryBuilder, ); ``` -------------------------------- ### Add Location FloatingActionButton Source: https://pub.dev/packages/geoflutterfire_plus/example A floating action button that, when pressed, displays a dialog to add a new location. If the button is pressed without a specific location context, it opens a dialog to add a new entry. ```dart FloatingActionButton( onPressed: () => showDialog( context: context, builder: (context) => const AddLocationDialog(), ), child: const Icon(Icons.add), ) ``` -------------------------------- ### Define Location and Geo Entity Classes Source: https://pub.dev/packages/geoflutterfire_plus Create Dart classes for your Firestore documents, including a nested 'geo' object, to enable type-safe data handling. ```dart /// An entity of Cloud Firestore location document. class Location { Location({ required this.geo, required this.name, required this.isVisible, }); factory Location.fromJson(Map json) => Location( geo: Geo.fromJson(json['geo'] as Map), name: json['name'] as String, isVisible: (json['isVisible'] ?? false) as bool, ); factory Location.fromDocumentSnapshot(DocumentSnapshot documentSnapshot) => Location.fromJson(documentSnapshot.data()! as Map); final Geo geo; final String name; final bool isVisible; Map toJson() => { 'geo': geo.toJson(), 'name': name, 'isVisible': isVisible, }; } /// An entity of `geo` field of Cloud Firestore location document. class Geo { Geo({ required this.geohash, required this.geopoint, }); factory Geo.fromJson(Map json) => Geo( geohash: json['geohash'] as String, geopoint: json['geopoint'] as GeoPoint, ); final String geohash; final GeoPoint geopoint; Map toJson() => { 'geohash': geohash, 'geopoint': geopoint, }; } ``` -------------------------------- ### Save geo data to Firestore Source: https://pub.dev/packages/geoflutterfire_plus Methods for adding or updating geographic data in Cloud Firestore collections. ```dart // Adds new documents to locations collection. GeoCollectionReference>( FirebaseFirestore.instance.collection('locations'), ).add({ 'geo': geoFirePoint.data, 'name': name, 'isVisible': true, }); ``` ```dart // Adds new documents to locations collection. FirebaseFirestore.instance.collection('locations').add( { 'geo': geoFirePoint.data, 'name': 'Tokyo Station', 'isVisible': true, }, ); ``` ```dart // Sets a new document by giving geoFirePoint.data to 'geo' field. GeoCollectionReference(FirebaseFirestore.instance.collection('locations')) .set( id: 'your-document-id', data: { 'geo': geoFirePoint.data, 'foo': 'foo', 'bar': 'bar', }, options: SetOptions(merge: true), ); // Updates an existing document's 'geo' field by giving GeoPoint instance. GeoCollectionReference(FirebaseFirestore.instance.collection('locations')) .updatePoint( id: 'your-document-id', field: 'geo', geopoint: GeoPoint(35.681236, 139.767125), ); ``` -------------------------------- ### Firestore Collection Reference Source: https://pub.dev/packages/geoflutterfire_plus/example Defines a reference to the 'locations' collection in Firestore. This can be used with or without a Firestore converter for type safety. ```dart final _collectionReference = FirebaseFirestore.instance.collection('locations'); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.