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

I am facing an issue with body-parser not properly processing my request in express.js

Utilizing the Controller in my project. Snippet from app.js: var express = require('express'); var app = express(); const routes = require('./Routes/route'); const bodyParser = require('body-parser'); app.use('/', ...

Is the jquery autocomeplete plugin malfunctioning when using numbers in the input?

I encountered a requirement to display stock number suggestions within a search box. To achieve this, I decided to implement the Jquery autocomplete plugin. Through an ajax call to a function in my cfc, I was able to retrieve all the stock numbers and stor ...

Move files in Node.js without removing the original source directory

Currently, I am facing an issue while attempting to transfer files from one directory to another using the mv module. The problem arises when the files are successfully moved, but the source directory is automatically deleted. My intention is for only the ...

Retrieve the value of a CSS class property regardless of whether it is actively being utilized

I am facing a dilemma where I need to determine the value of the 'width' property for a css class named 'foo' (example: ".foo { width:200px}" ). However, there may not be an element with this class in the dom yet. My goal is to retrie ...

Tips for adjusting the color of multi-line text when hovering with the mouse

I'm facing a challenge in changing the color of text when someone hovers over it, but so far I've only been able to make it work if the mouse scrolls over the top border of the text. The text I'm testing is located in the top left corner an ...

Troubleshooting the issue with utilizing the ng-repeat directive to loop through images in Angular JS

Embarking on my initial website development journey with Java and Spring Boot, I've hit a stumbling block in the front-end realm. Being a newbie, I'm struggling to identify and resolve the issue at hand. Problem title: How do I ...

Express encountered an unexpected error when attempting to navigate to the client directory

I am attempting to send the index.html file from my client directory, located at the same level as my server directory. However, I am encountering the following error: TypeError: undefined is not a function at Object.handle (/myapp/server/routes/routes.js ...

Stop the form from submitting when the enter key is pressed using VueJS and Semantic UI

After spending the past two days searching for a solution to this persistent issue, none of the suggested remedies have proven effective so far. My form's HTML structure is as follows: <form id="quote_form" action="" method="get" class="ui large ...

Learn the process of integrating VueJS with RequireJS

I am attempting to set up VueJS with RequireJS. Currently, I am using the following VueJS library: . Below is my configuration file for require: require.config({ baseUrl : "js", paths : { jquery : "libs/jquery-3.2.1.min", fullcalendar : "libs/ful ...

What are some ways I can improve the readability of this if-else function in Javascript ES6?

As a newcomer to React development, I am currently in the process of tidying up my code. One issue that I am facing is how to deal with a particular function while minimizing the use of if-else statements. const calculatePerPage = () => { if ...

Tally up the occurrences of each item in the array and provide the result in the form

Is there a built-in method in JavaScript to convert an array like: const colorArray = ['red', 'green', 'green', 'blue', 'purple', 'red', 'red', 'black']; into an object that c ...

Even though the onSubmit attribute is set to false in the HTML form, it still submits

I've been struggling with a form that just won't stop submitting, no matter what I do. I have checked similar questions on SO, but none of the solutions seem to work for me. It's frustrating because it's such a simple task. The reason w ...

Using JavaScript to assign multiple classes to a function at separate intervals

I'm trying to add two classes to a JavaScript function, but I'm encountering some issues. When I try to add both classes in the same line, only one of them works. However, if I add each class on separate lines within the function, only the second ...

Encountered a snag with submitting data via AJAX: received an error message stating

I created this custom script for a contact form on my website, and it seems to be working fine. However, I'm encountering an issue where instead of storing the data in my database, all I get is [object HTMLCollection]. Can someone please explain wh ...

Creating a custom login directive in Angular 2 and utilizing location.createComponent for dynamic

Incorporating a login system into my Angular app has been a priority for me lately. I came across a helpful resource here that outlines the process. However, I encountered an issue with the custom RouterOutlet directive as shown below: import { ElementRef ...

Encountering Issues with Accessing Property

Upon trying to run my code, the console is displaying an error that I am unable to resolve. The error specifically states: "TypeError: Cannot read property 'author' of undefined." View the StackBlitz project here The error seems to be coming fr ...

Upon successful authorization, the Node Express server will pass the access token to the React client app via OAuth in the callback

I am currently working on a node server that authenticates with a third party using oauth, similar to how Stack Overflow does. After authorizing the request and obtaining the access token and other essential information from the third party, my goal is to ...

Organizing requests in PHP: What are the best methods?

My attempt to use the code below for queuing requests has not produced the desired results! <?php $Sleep_Time = "10"; if (isset($_POST["String"])){ $File = "Edit_File_Content.txt"; while(file_exists($File . "_L ...

Ways to verify if a minimum of three letters in each variable correspond

let nameOne = 'chris|'; let nameTwo = 'christiana'; To use JavaScript, what is the best way to determine if three or more letters match between both variables? ...

Issue: Unable to use the b.replace function as it is not recognized (first time encountering this error)

I can't seem to figure out what I'm doing wrong. It feels like such a silly mistake, and I was hoping someone could lend a hand in solving it. Here is my controller - I'm utilizing ng-file-upload, where Upload is sourced from: .controller( ...