Search code examples
firebasefirebase-realtime-databaseflutter-layout

How to perform some calculations in firebase realtime database before fetching data and fetch data accordilngly


Database sturucture

I have a realtime database working with flutter app in frontend.Here with latitiude and longitudes data of different people.

I want to read this data in a way that I only fetch the data(longitude & longitude) of the person who is atmost 100 meters away from the user.I am gonna have a large number of data in my database.

One way I can use is to fetch all the data in my flutter app and filter accordingly by doing calculations using haversine formula on the app itself (but I guess that would be too inieffcient).

Is there a way to do calculations in the database and fetch only the data which is needed i.e only the coordinates that are atmost 100 meters away.

In other words I want to apply the haversine formula in the backend itself and fetch only the data which gives result less than 100.

OR do I need to change my approach.

I am new to flutter and firebase.Any help will be appreciated.

I have tried using filtered and sorted queries but I couldn't persorm calculations on the backend by using them


Solution

  • You should use a geocoder. Pass a persons lat/long as the center point of a 50 meter radius boundary. Then, query for all people (by lat/long) within the bounds of that radius.

    You can do this using the geofire package with Cloud Firestore.

    Alternatively, you could write a Firebase Function and use node-geocoder in a very similar manner.

    There are several Flutter geocoder plugins as well. I have not used these Flutter plugins but the procedure is almost identical based on their docs.