Utilizing a custom function to filter Firestore collection data based on location proximity

I have a question about filtering a Firestore collection using a function where the values of the documents in the collection are used as arguments. Let's say we have a Firestore collection with documents structured like this:

{
  pointOfInterest: "Some string label"
  longitude: -100.123
  latitude: 50.456
}

In addition, I have code that retrieves a user's geocoordinates (in my case, using react-native), such as:

const getCurrentLatLong = () => {
    // do some stuff, then...
    return { latitude: someNumber, longitude: someOtherNumber }
}

What I want to achieve is to filter the Firestore collection based on the distance between each document's coordinates and the current user location. Ideally, I would like to do something like this:

let currentLocation = getCurrentLatLong()
let filteredSet = firebase
    .firestore()
    .collection('MyCollection')
    // filtering each individual document 
    .filter(function (document, currentLocation) {
         let docLat = document.latitude
         let docLong = document.longitude
         return distance(
             {latitude: docLat, longitude: docLong},
             currentLocation) 
             < SOME_CONST_DISTANCE
     })

This way, I would end up with a filteredSet containing all the documents in the collection that are within a certain distance from the current user's location.

I've done some research and found some potential starting points ( and https://firebase.google.com/docs/reference/js/firebase.database.Query#on), but I'm unsure how to implement what's discussed in those resources. Any advice or documentation on how to accomplish this would be greatly appreciated.

Answer №1

It is not currently possible to pass a function into Cloud Firestore for filtering documents. You can only pass in static values or filter the documents client-side after reading them all.

If you are trying to perform a geoquery, which involves returning documents based on their distance from a known point, this functionality is not natively supported in Cloud Firestore yet. Although it does have support for a geographical point data type, creating such queries yourself may be inefficient at the moment.

To explore more on this topic:

  • Some developers have adapted Firebase's GeoFire library for use with Firestore. Check out How to run a geo "nearby" query with firestore?.
  • I presented a talk on this subject in the past, available on YouTube: https://www.youtube.com/watch?v=mx1mMdHBi5Q
  • For more information, visit AngularFirebase.com for a guide on Realtime GeoQueries With Firestore

Answer №2

As mentioned before, Firestore currently does not have built-in support for geo queries. However, I wanted to share a project that I have been developing which aims to address this limitation...

https://github.com/mbramwell1/GeoFire-Android

This tool allows you to perform standard Firestore queries as well as search by location coordinates. Take a look at it and see if it meets your requirements.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Connecting Angularfire2 with Firestore for advanced querying

Glad you stopped by! Currently, I have two Firestore Collections set up in my Angularfire2 application. One consists of "Clients", while the other contains "Jobs". Each client can have multiple jobs assigned to them, and vice versa. I've been workin ...

Error Unhandled in Node.js Application

I have encountered an issue in my NodeJS application where I have unhandled code in the data layer connecting to the database. I deliberately generate an error in the code but do not catch it. Here is an example: AdminRoleData.prototype.getRoleByRoleId = ...

Strategies for iterating over an array in React with TypeScript

I'm currently working on looping through an array to display its values. Here's the code I have: ineligiblePointsTableRows() { return this.state[PointsTableType.INELIGIBLE].contracts.map(contract => { return { applied: (&l ...

There seems to be this strange and unexpected sharing of Animated.View and useRef between different child components

Currently, I am displaying a list of items in the following manner: {formattedJournal[meal].map((food, idx, arr) => { const isLast = idx === arr.length - 1; return ( <View key={idx}> ...

Establishing relationships with Sequelize between tables in different schemas

Currently, I am working on a project that involves using Sequelize and PostgreSQL as the database. In this project, I have implemented dynamic schema creation whenever a new user registers on the website. Specifically, I have a table called user_credentia ...

Verifying the numerical value of a decimal place

How can I determine if the 4th decimal place in a number is zero or not? I want to throw an error message if it is not zero. For instance, in the number 2.3189, the value of the 4th decimal place is 9. My current code works for most cases, but for exampl ...

Techniques for accessing the most recent input values within a loop

Here is the HTML code snippet: <div v-for="item in my_items"> <div> <input type="text" :value=item.name /> </div> <div> <button @click="edit(item.id, item.name)">Edit ...

Best Practices for Handling URL-Encoded Form Data in the Latest Version of Next.js

Currently delving into Next.js 13, I've implemented a form within my application for submitting a username and password to the server. The form's action path is designated as /submit with a POST request method. Yet, I'm encountering difficul ...

A Smarter Approach to Updating Text Dynamically with JavaScript and Vue

Currently, I am utilizing Vue to dynamically update text by using setInterval() in combination with a data property. The method I have in place is functional, but I am curious if there exists a more efficient way to optimize it. Is the current code as stre ...

The click function for the parent div will not be executed if I click on the child div

Hey, I encountered an issue in my code that I need help with. $(document).ready(function() { $(document).on('click', '.rohit', function() { alert('rohit'); }) $(document).on('click', '.azad', ...

Tips for optimizing large image files on a basic HTML, CSS, and JavaScript website to improve site speed and ensure optimal loading times

Currently, my site is live on Digital Ocean at this link: and you can find the GitHub code here: https://github.com/Omkarc284/SNsite1. While it functions well in development, issues arise when it's in production. My website contains heavy images, in ...

Is it possible to utilize the useRef Hook for the purpose of storing and accessing previous state values?

If you have already implemented the useState and useEffect Hooks for maintaining previous state, another approach is to utilize the useRef Hook to track previous state values as well. ...

What is the reasoning behind having two separate permission dialog boxes for accessing the webcam and microphone in flash?

I am currently using a JavaScript plugin known as cameratag () in order to record videos through the web browser. This plugin utilizes a flash-based solution. When the flash application requests permission to access the webcam, it presents a security dialo ...

Challenges arise when incorporating interfaces within a class structure

I created two interfaces outside of a class and then proceeded to implement them. However, when I tried to assign them to private properties of the class, something went wrong and I'm unable to pinpoint the issue. Can anyone offer assistance with thi ...

Communication between Laravel and controller using AJAX for exchanging information

I have a specific AJAX function being called from a view: function gatherProductData() { var productIds = []; $('#compare-widget tbody tr').each(function(i, ele) { productIds[i] = $(ele).data('product-id'); }); ...

Guide on how to smoothly navigate through an HTML page to a specific anchor point

Is there a way to use JavaScript to make the browser scroll the page to a specific anchor? In my HTML code, I have set either a name or id attribute like this: <a name="anchorName">..</a> or <h1 id="anchorName2">..&l ...

Adjusting the array of buttons with various functions within the Header component

I am looking to create a customizable Header component with different sets of buttons that trigger various functions. For example, on the home page, the buttons could be "visit about page" and "trigger vuex action A", while on the about page they could be ...

What's the best way to invoke a function from a different JS file or create a custom event in JQuery that includes a parameter as a data object?

I am facing an issue while using requireJS to call a function from a required JS file. In my main app.js "controller", I have included (plugin)app.js, which contains all plugin configurations and related functions. The snippet below is from app.js defin ...

Is it possible to programmatically refresh an Angular controller?

Within my HTML page, I have implemented three tabs with each tab linked to a unique controller. The structure is as follows: MainHTML (app.pages.managing.html): <div id="DetailsViewContainer"> <div ng-if="selectedTab === 'tab1&a ...

Tips for properly formatting functional Vue components?

Below is a functional component that functions as intended. <template functional> <div> <input /> </div> </template> <script> export default { name: "FunctionalComponent" } </script> <styl ...