iTranslated by AI
Introducing geoflutterfire_plus: A Flutter Package for Firestore Geo-queries
geoflutterfire_plus Package
In this article, I will introduce geoflutterfire_plus, a pub package developed and released by the author that enables location-based queries in Flutter x Firestore. I'll summarize its primary usage and present a sample application.
By using this package, you can take:
- Center position (latitude and longitude)
- Detection radius (km)
- (Optional) Other filter conditions
as inputs and perform real-time retrieval (or request-based fetching) of location information stored in Cloud Firestore using the Geohash mechanism.
It can be widely used in apps that search for location data on a map, as shown in the following GIF.

Background of geoflutterfire_plus Development
A similar package named geoflutterfire already exists.
However, at the time of writing, this package's maintenance has been stalled for about a year. Crucial dependency packages like cloud_firestore are not updated to their latest versions. Consequently, if your application uses a newer version of cloud_firestore, a dependency conflict will occur, making it unusable.

I considered continuously creating PRs to update the dependencies. However, upon reading the internal source code closely, I found many areas where the code and design could be fundamentally improved. For a while, I used a fork that I improved myself. As those fixes matured, I decided to rewrite the package from scratch and publish it, which led to the development of this package.
There is also a package called geoflutterfire2, which primarily focuses on maintaining the dependencies.
However, its basic code remains the same as the original geoflutterfire package.
About Geohash and Geo query
In this chapter, I will briefly explain the Geohash and Geo query mechanisms used by the geoflutterfire_plus package to run location-based queries, while providing some helpful reference information.
If you just want to use the geoflutterfire_plus package to develop location-based apps in Flutter, you can read this briefly or skip it and come back when you become curious about the internal workings of the package.
Here are some helpful links regarding Geohash and Geo query:
When performing a location-based search, you might naturally think of saving latitude and longitude information and writing a query that filters points within a detection range from a given center by calculating the distance between two points.
However, in Cloud Firestore, only one range condition can be applied to a single composite query. Therefore, if you save latitude and longitude as separate fields, you cannot write a query like "latitude is within this range AND longitude is within this range."
To address this, Geohash is used—a system that converts a pair of latitude and longitude values into a single string.
Geohash is a Base32 string created by encoding the latitude and longitude of a location. Generally, when we think of "encoding," we imagine that inputs and outputs are scrambled (meaning you can't predict inputs or their relationships from the outputs). However, Geohash has the characteristic that the closer physical locations are, the more similar their Geohash strings will be. Following the details of the algorithm makes the reason for this easy to understand.
For example, if you provide the latitude and longitude of Tokyo Station as (35.681236, 139.767125), the corresponding Geohash string is xn76urx66. Shibuya Station has coordinates (35.658034, 139.701636), and its Geohash string is xn76fgreh.
While Geohash is calculated from latitude and longitude, the algorithm discards some information, so the location indicated by a Geohash is not a specific point but a rectangular area corresponding to its precision. The more detailed the latitude and longitude provided, the higher the precision (number of characters) of the Geohash string.
Since the Earth is spherical, actual values vary depending on the location (latitude). However, the correspondence between Geohash precision (number of characters) and the size of the rectangular area representing the maximum error range at the equator (Height: North-South [km] x Width: East-West [km]) is as follows:
| Digits | Rectangular Area |
|---|---|
| 1 | Approx. 5,000km x Approx. 5,000km |
| 2 | Approx. 1,250km x Approx. 625km |
| 3 | Approx. 156km x Approx. 156km |
| 4 | Approx. 39.1km x Approx. 19.5km |
| 5 | Approx. 4.89km x Approx. 4.89km |
| 6 | Approx. 1.22km x Approx. 0.61km |
| 7 | Approx. 153m x Approx. 153m |
| 8 | Approx. 38.2m x Approx. 19.1m |
| 9 | Approx. 4.77m x Approx. 4.77m |
We can see that a precision of about 7 digits is sufficient for location-based services.
When performing a location query, the geoflutterfire_plus package is implemented to retrieve documents within a specified radius from a given center point by performing startAt and endAt queries against these Geohash strings.
Introduction to Basic Features and Usage
This chapter introduces the basic features and usage of the geoflutterfire_plus package.
For clarity, type annotations are written redundantly in the explanations.
Handling Latitude and Longitude
Since geoflutterfire_plus depends on the cloud_firestore package, you should use the GeoPoint class defined in cloud_firestore when handling latitude and longitude information. geoflutterfire_plus also uses it internally.
The GeoPoint class is a simple class that holds latitude and longitude as members.
// Latitude and longitude of Tokyo Station.
const GeoPoint tokyoStation = GeoPoint(35.681236, 139.767125);
Handling Location Information in Cloud Firestore (GeoCollectionReference)
Handling location information in Cloud Firestore means saving such data in some collection.
For instance, if a top-level collection named locations is responsible for this, you can define a reference to that collection using the GeoCollectionReference class provided by the geoflutterfire_plus package.
The constructor of GeoCollectionReference requires a standard CollectionReference<T> type reference from the cloud_firestore package.
// Define CollectionReference as usual.
final CollectionReference<Map<String, dynamic>> collectionReference =
FirebaseFirestore.instance.collection('locations');
// Define GeoCollectionReference.
final GeoCollectionReference<Map<String, dynamic>> geoCollectionReference =
GeoCollectionReference(collectionReference);
It also supports adding types using withConverter. Assuming you have a Location class with fromDocumentSnapshot and toJson methods, it would look like this:
// Definition of the Location class. Check the link below for details.
class Location {
// ... omitted
}
// Define a typed CollectionReference as usual.
CollectionReference<Location> typedCollectionReference =
FirebaseFirestore.instance.collection('locations').withConverter<Location>(
fromFirestore: (ds, _) => Location.fromDocumentSnapshot(ds),
toFirestore: (obj, _) => obj.toJson(),
);
// Define a typed GeoCollectionReference.
final GeoCollectionReference<Location> typedGeoCollectionReference =
GeoCollectionReference(typedCollectionReference);
If you want to see a specific implementation example of the Location class, please refer to the relevant part of the following file:
Defining Location Data (GeoFirePoint)
The geoflutterfire_plus package defines a class called GeoFirePoint for handling location information.
A GeoFirePoint instance can be created by passing a GeoPoint (latitude and longitude) to the constructor. It includes features like .geohash to calculate and return its Geohash string, and .data to return a set containing the GeoPoint and the Geohash string.
As shown in the example below, you can obtain the Geohash string for a location simply by calling geoFirePoint.geohash.
// Latitude and longitude of Tokyo Station.
const GeoPoint tokyoStation = GeoPoint(35.681236, 139.767125);
// Define a GeoFirePoint by passing a GeoPoint instance.
const GeoFirePoint geoFirePoint = GeoFirePoint(tokyoStation);
// Get the Geohash. Outputs the Geohash string 'xn76urx4r' for Tokyo Station.
print(geoFirePoint.geohash);
// Returns a Map<String, dynamic> containing the GeoPoint and Geohash string.
// <String, dynamic>{
// 'geopoint': GeoPoint(35.681236, 139.767125),
// 'geohash': xn76urx4r
// }
print(geoFirePoint.data);
Saving Location Data (add, set)
Next, I will introduce how to save location data.
That said, you simply use the GeoCollectionReference.add method. In terms of internal implementation, it is equivalent to simply using the CollectionReference.add method.
By saving the Geohash string using GeoFirePoint.data at this point, you can later write location queries relying on that Geohash string.
Future<DocumentReference<Map<String, dynamic>>> addGeoData() async {
final CollectionReference<Map<String, dynamic>> collectionReference =
FirebaseFirestore.instance.collection('locations');
final GeoCollectionReference<Map<String, dynamic>> geoCollectionReference =
GeoCollectionReference<Map<String, dynamic>>(collectionReference);
const GeoPoint tokyoStation = GeoPoint(35.681236, 139.767125);
const GeoFirePoint geoFirePoint = GeoFirePoint(tokyoStation);
// Call the add method of GeoCollectionReference.
// The Map<String, dynamic> data from geoFirePoint.data
// is saved in the Cloud Firestore document.
return geoCollectionReference.add(geoFirePoint.data);
}
Similarly, we provide the GeoCollectionReference.set method, which corresponds to CollectionReference.doc('your-document-id').set (DocumentReference.set). This also uses the CollectionReference.set method internally and is simple to use.
Future<void> setGeoData() async {
// ... omitted
// Call the set method of GeoCollectionReference.
// The Map<String, dynamic> data from geoFirePoint.data
// is saved in the Cloud Firestore document.
// cloud_firestore's [SetOptions] can be used similarly.
return geoCollectionReference.set(
id: 'your-document-id',
data: geoFirePoint.data,
options: SetOptions(merge: false),
);
}
Updating Location Data (update)
Next, I will introduce how to update already saved location data.
Specify the field name that includes the location data, provide the location you want to update as a GeoPoint, and call the GeoCollectionReference.updatePoint method. Internally, it also uses the CollectionReference.doc('your-document-id').update (DocumentReference.update) method, and only the specified field will be updated.
Note that using this method only requires providing a GeoPoint (latitude and longitude information), and it will internally calculate and update the Geohash for that point automatically.
Future<void> updateGeoData() async {
// Want to update with the latitude and longitude of Tokyo Station.
const GeoPoint tokyoStation = GeoPoint(35.681236, 139.767125);
// Call the update method of GeoCollectionReference.
// Update the specified 'geo' field with the latitude and longitude of Tokyo Station.
return geoCollectionReference.updatePoint(
id: 'your-document-id',
field: 'geo',
geoPoint: tokyoStation,
);
}
Deleting Location Data (delete)
To delete a document, simply call the GeoCollectionReference.delete method. Internally, it uses the CollectionReference.doc('your-document-id').delete (DocumentReference.delete) method. Therefore, you don't have to use this method from geoflutterfire_plus specifically; you can also use the DocumentReference.delete method from the cloud_firestore package.
Future<void> deleteGeoData() async {
// ... omitted
// Call the delete method of GeoCollectionReference.
return geoCollectionReference.delete(id: 'your-document-id');
}
Fetching Location Data (list)
Finally, I will introduce how to fetch location data.
By following the methods described above, location data should be saved in a specific collection in Cloud Firestore, within a field of a particular name (the geo field in the example above), containing a GeoPoint value (latitude/longitude) and a Geohash string in a Cloud Firestore map type (≈ Dart's Map type).
To fetch documents located within a specified radius R [km] (radiusInKm) from a given center position (center) among these saved location data, the geoflutterfire_plus package provides the following two methods:
- Method to fetch on demand as a
Future:GeoCollectionReference.fetchWithin - Method to subscribe in real-time as a
Stream:GeoCollectionReference.subscribeWithin
Fetching on demand (Future)
The return value is of type Future<List<DocumentSnapshot<T>>>. The generic type T depends on what type you have assigned to GeoCollectionReference. If no specific type is assigned, it will likely be Map<String, dynamic>. If you are using withConverter, it will be the type specified there.
The required parameters are as follows:
- Center position:
center(GeoFirePointtype) - Detection radius (km):
radiusInKm(doubletype) - Field name:
field(Stringtype) - Function to create a
GeoPointinstance from aTtype object:geopointFrom(GeoPoint Function(T obj)type)
The last parameter, geopointFrom of type GeoPoint Function(T obj), is a bit complex, so I'll add an explanation.
This requires a function to generate a GeoPoint instance from a T type object (as mentioned above, this will be the type assigned to GeoCollectionReference with withConverter, or Map<String, dynamic> if no type is assigned).
For example, if you haven't assigned a specific type and are saving the GeoPoint value under the key geopoint within a map-type field named geo in the target document, you would write it like this:
GeoPoint Function(Map<String, dynamic> data) geopointFrom =
(data) => (data['geo'] as Map<String, dynamic>)['geopoint'] as GeoPoint;
For example, if the document has a type Location and you can obtain the GeoPoint value via location.geo.geopoint, you would write it like this:
GeoPoint Function(Location location) geopointFrom =
(location) => location.geo.geopoint;
Therefore, the method to fetch only data located within a 50 km radius of Tokyo Station from the documents in the locations collection (assuming map-type data equivalent to GeoFirePoint.data is saved in the geo field) is as follows:
Future<List<DocumentSnapshot<Map<String, dynamic>>>> fetchGeoData() async {
const GeoPoint center = GeoPoint(35.681236, 139.767125);
final CollectionReference collectionReference =
FirebaseFirestore.instance.collection('locations');
return GeoCollectionReference(collectionReference).fetchWithin(
center: const GeoFirePoint(center),
radiusInKm: 50,
field: 'geo',
geopointFrom: (data) =>
(data['geo'] as Map<String, dynamic>)['geopoint'] as GeoPoint,
strictMode: true,
);
}
There is an optional parameter strictMode of type bool. It defaults to false. When false, a radius with a buffer of 1.02 times the actual detection range is used as the search area. When true, the detection is performed with the exact specified radius without a buffer.
By the way, this Future-based on-demand fetch method is a new feature added in geoflutterfire_plus.
Unlike the Stream-based subscription explained in the next section, it fetches data only at the time of the request. Use it when it leads to optimized read costs or user experience.
Please also refer to the doc comments in the package for an explanation of each parameter.
Real-time retrieval (Stream)
Next, I will introduce the GeoCollectionReference.subscribeWithin method, which returns the results of real-time retrieval as a Stream type.
The return value is of type Stream<List<DocumentSnapshot<T>>>.
The usage is exactly the same as the on-demand fetch method GeoCollectionReference.fetchWithin.
Stream<List<DocumentSnapshot<Map<String, dynamic>>>> subscribeGeoData() async {
const GeoPoint center = GeoPoint(35.681236, 139.767125);
final CollectionReference collectionReference =
FirebaseFirestore.instance.collection('locations');
return GeoCollectionReference(collectionReference).subscribeWithin(
center: const GeoFirePoint(center),
radiusInKm: 50,
field: 'geo',
geopointFrom: (data) =>
(data['geo'] as Map<String, dynamic>)['geopoint'] as GeoPoint,
strictMode: true,
);
}
Use this, for example, when you want to retrieve location data in real-time while manipulating the search center or radius through the user interface.
Adding arbitrary filter conditions (where clauses)
So far, I have introduced basic methods for on-demand fetching and subscription of location data.
In the GeoCollectionReference.fetchWithin and GeoCollectionReference.subscribeWithin methods of geoflutterfire_plus, you can add arbitrary filter conditions using the optional parameter queryBuilder of type Query<T>? Function(Query<T> query)?.
For example, if you want to filter only documents where the isVisible field is true in a location query similar to those mentioned above, specify a function for the queryBuilder parameter that receives a Query<T> object named query and returns a new Query<T> object with added filter conditions (like where clauses) as follows:
Future<List<DocumentSnapshot<Map<String, dynamic>>>> fetchVisibleGeoData() async {
const center = GeoPoint(35.681236, 139.767125);
final collectionReference =
FirebaseFirestore.instance.collection('locations');
return GeoCollectionReference(collectionReference).fetchWithin(
center: const GeoFirePoint(center),
radiusInKm: 50,
field: 'geo',
geopointFrom: (data) =>
(data['geo'] as Map<String, dynamic>)['geopoint'] as GeoPoint,
// Add where('isVisible', isEqualTo: true) filter condition
queryBuilder: (query) => query.where('isVisible', isEqualTo: true),
strictMode: true,
);
}
Note that such queries require composite indexes. If you execute it without such an index being generated, an error will occur with a message like "[cloud_firestore/failed-precondition] The query requires an index...". A link to create the corresponding index should be displayed in that error message on the console; clicking it to generate the index and then running it again should work as expected.
Compatibility with the geoflutterfire package (also as a migration guide)
I will add this later.
Sample App Using geoflutterfire_plus
In this chapter, we will briefly look at how to build an app using the geoflutterfire_plus and google_maps_flutter packages. This is an app that displays location data retrieved via the features of the geoflutterfire_plus package in real-time on Google Maps.
Basically, this is an excerpt from the example project in the geoflutterfire_plus repository, so you can check the details at the following link:
Please add the latest versions of the geoflutterfire_plus and google_maps_flutter packages to your pubspec.yaml. The same applies to cloud_firestore, firebase_core, and rxdart.
dependencies:
cloud_firestore: <latest-version-here>
firebase_core: <latest-version-here>
flutter:
sdk: flutter
geoflutterfire_plus: <latest-version-here>
google_maps_flutter: <latest-version-here>
rxdart: <latest-version-here>
For the google_maps_flutter package, please check the package README carefully, obtain an API key from GCP's maps-platform, and complete the necessary settings for both iOS and Android.
We assume that the location data for the sample app is saved in a top-level locations collection in Cloud Firestore with the following schema.
As explained in the previous section on adding location data, the geo field stores the Geohash string and the GeoPoint value (equivalent to GeoFirePoint.data). (Additionally, name and isVisible fields have been added.)

The entry point and surrounding code are as follows. The Example widget is a StatefulWidget that displays the map screen.
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
runApp(const App());
}
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(),
);
}
}
The primary members (states) of the State class are:
- Fetched markers on Google Maps:
_markers(typeSet<Marker>) - Object to subscribe to and hold query conditions:
_geoQueryCondition(typeBehaviorSubject<_GeoQueryCondition>)- The
_GeoQueryConditiontype encapsulates the following:- Detection radius:
_radiusInKm(typedouble) - Camera position on Google Maps:
_cameraPosition(typeCameraPosition)
- Detection radius:
- The
- Subscription to query results:
_stream(typeStream<List<DocumentSnapshot<Map<String, dynamic>>>>)
The approach involves updating the detection radius (km) and camera position (= center of the location query), pushing them into the _geoQueryCondition BehaviorSubject, and then updating the _markers—a collection (Set) of Marker objects from the google_maps_flutter package—with the resulting real-time location data.
We use _geoQueryCondition.switchMap to create a Stream for location queries based on the latest detection radius and center position. The usage of the GeoCollectionReference.subscribeWithin method is as explained earlier.
Also, remember to override the dispose method to close the _geoQueryCondition.
/// A class to handle detection radius and camera position together as query conditions.
class _GeoQueryCondition {
_GeoQueryCondition({
required this.radiusInKm,
required this.cameraPosition,
});
final double radiusInKm;
final CameraPosition cameraPosition;
}
class Example extends StatefulWidget {
const Example({super.key});
@override
ExampleState createState() => ExampleState();
}
class ExampleState extends State<Example> {
/// List of markers on Google Maps.
Set<Marker> _markers = {};
/// [BehaviorSubject] to hold the latest query conditions while subscribing to them.
final _geoQueryCondition = BehaviorSubject<_GeoQueryCondition>.seeded(
_GeoQueryCondition(
radiusInKm: _initialRadiusInKm,
cameraPosition: _initialCameraPosition,
),
);
/// Subscription to query results. Defined as late final because it uses this._geoQueryCondition.
late final Stream<List<DocumentSnapshot<Map<String, dynamic>>>> _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<String, dynamic>)['geopoint'] as GeoPoint,
strictMode: true,
),
);
@override
void dispose() {
_geoQueryCondition.close();
super.dispose();
}
}
In the build method, the GoogleMap widget from the google_maps_flutter package is displayed.
In onMapCreated, which is of type void Function(GoogleMapController)?, we start subscribing to _stream (the query results). Every time new query results are received, the _updateMarkersByDocumentSnapshots method updates the _markers set, and setState is called.
In onCameraMove, which is of type void Function(CameraPosition)?, the updated camera position (CameraPosition) is obtained each time. We pass this to _geoQueryCondition.add to feed it as a new query condition into the BehaviorSubject.
This enables real-time acquisition of location data while dynamically changing the center position.
// ... omitted
class ExampleState extends State<Example> {
// ... omitted
@override
Widget build(BuildContext context) {
return Scaffold(
body: Stack(
children: [
GoogleMap(
// ... some properties are omitted
initialCameraPosition: _initialCameraPosition,
onMapCreated: (_) =>
_stream.listen(_updateMarkersByDocumentSnapshots),
markers: _markers,
onCameraMove: (cameraPosition) {
_geoQueryCondition.add(
_GeoQueryCondition(
radiusInKm: _radiusInKm,
cameraPosition: cameraPosition,
),
);
},
),
// ... omitted
],
),
);
}
/// Updates [_markers] by fetched geo [DocumentSnapshot]s.
void _updateMarkersByDocumentSnapshots(
List<DocumentSnapshot<Map<String, dynamic>>> documentSnapshots,
) {
final markers = <Marker>{};
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<String, dynamic>)['geopoint'] as GeoPoint;
markers.add(_createMarker(id: id, name: name, geoPoint: geoPoint));
}
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: () {/** omitted */},
);
}
If you want to update the detection radius, you can set it up so that a method like the following is called.
// ... omitted
class ExampleState extends State<Example> {
// ... omitted
/// Updates the detection radius.
void updateRadius(double radius) => _geoQueryCondition.add(
_GeoQueryCondition(
radiusInKm: value,
cameraPosition: _cameraPosition,
),
);
}
Conclusion
I have introduced the geoflutterfire_plus package and its usage. I plan to update this article as the package is updated.
It serves as a great motivation for future development, so I would be delighted if you could give a LIKE 👍 on the pub.dev package page or a star to the GitHub repository!
I also welcome any questions, bug reports, or Pull Requests regarding the package on the corresponding GitHub repository.
Discussion
geoflutterfireのメンテナンスがされていない件で困っていたので非常に助かりました!
こちらの記事を参考に、簡単でわかりやすい実装ができて感動しております。
一部期待した動作をしないものがあり質問なのですが、
こちら「queryBuilder」の中で「orderBy」は禁止でしょうか?指定すると何も返ってこず。。
追記:
Limitation: currently limit and orderBy queries are not supported because of the geo hash query algorithm and Cloud Firestore query limitations. Alternatively documents can be sorted on client side after getting the data (documents).
こちらに書いてありましたね。
クライアント側でソートするようにします!
コメントありがとうございます!
そうなんです
orderByは中のアルゴリズムと Cloud Firestore のクエリの書き方の制約のために使えずでして...🙏問い合わせが多い内容でもあるので、もしいい案を思いつくことがあれば対応します or PR などもお待ちしています!!