Search code examples
javaandroidfirebasegoogle-cloud-firestoregeofirestore

Retrieve users from Firestore within a range using GeoFireStore Android


In my Android application, I need to get a list with users from Firestore within a range using GeoFireStore.

Database structure in Firestore: enter image description here

All the information I got from this link.

Dependency:

implementation 'com.github.imperiumlabs:GeoFirestore-Android:v1.1.1'

Repositories:

maven { url 'https://jitpack.io' }

A code:

CollectionReference geoFirestoreRef = 
FirebaseFirestore.getInstance().collection("Users");
GeoFirestore geoFirestore = new GeoFirestore(geoFirestoreRef);

GeoQuery geoQuery = geoFirestore.queryAtLocation(new GeoPoint(32.848971, 35.0920935), 30);

geoQuery.addGeoQueryDataEventListener(new GeoQueryDataEventListener() {
    @Override
    public void onDocumentEntered(DocumentSnapshot documentSnapshot, GeoPoint location) {
    }

    @Override
    public void onDocumentExited(DocumentSnapshot documentSnapshot) {  
    }

    @Override
    public void onDocumentMoved(DocumentSnapshot documentSnapshot, GeoPoint location) { 
    }

    @Override
    public void onDocumentChanged(DocumentSnapshot documentSnapshot, GeoPoint location) {    
    }

    @Override
    public void onGeoQueryReady() {     
    }

    @Override
    public void onGeoQueryError(Exception exception) {
    }
});

So I didn't do I can't to call a function:

@Override
public void onDocumentEntered(DocumentSnapshot documentSnapshot, GeoPoint location) {
}

Only this function is called:

@Override
public void onGeoQueryReady() {     
}

Solution

  • I'm adding this as an answer because I can't add comments.

    So, what you're trying to do is getting all the DocumentSnapshots within a certain radius, for this your code is correct, you create a new GeoFirestore instance using a CollectionReference, and then you query the location you want.

    The problem is that in your database currently there is no location data usable by GeoFirestore; you can solve this by appending the "location data" when you add your document to the database.

    implementation 'com.github.imperiumlabs:GeoFirestore-Android:v1.2.0'
    /*
     * You have to do this only one time for document
     * so the best is after the document upload to Firestore.
     */
    
    //The id of the document you want to add the location
    String documentId = documentReference.id;
    GeoPoint point = new GeoPoint(/*lat,long of your point*/);
    geoFirestore.setLocation(documentId, point);
    

    You can find the official documentation here.

    As the last tip, I suggest you update the library to the correct version (1.2.0) because the geo hashing algorithm is changed and you can take advantage of the kotlin capability.