4

I've got the following Google Firestore database structure: enter image description here

Is there a way to query by a range of each - latitude and longitude? For example I want to get all users which have location.lat and location.lng in the range of: 51.400 to 52.000 and -0.100 to -0.300. Can anyone please help me figure out the query needed to do that?

I hope this question makes any sense. Any help appreciated.

Edit: I am not using a 'Geographical point' data type. I am using a custom object with 2 float numbers and want to do a simple number compare. The thing is that I do not know (and cannot find) a way how to build my query.

Paul Strupeikis
  • 275
  • 3
  • 11
  • What you're describing is known as a geoquery, and Firestore doesn't support them yet. See https://stackoverflow.com/questions/46607760/how-to-query-closest-geopoints-in-a-collection-in-firebase-cloud-firestore/46608540#46608540 – Frank van Puffelen Nov 07 '17 at 19:51
  • Possible duplicate of [How to query closest GeoPoints in a collection in Firebase Cloud Firestore?](https://stackoverflow.com/questions/46607760/how-to-query-closest-geopoints-in-a-collection-in-firebase-cloud-firestore) – Frank van Puffelen Nov 07 '17 at 19:52
  • 1
    Appreciate your comment Frank, but I was aware of that. A 'location' field in my case is a custom object which stores two numbers. I want to do a simple '>' or '<' compare between two numbers. – Paul Strupeikis Nov 07 '17 at 22:09

2 Answers2

13

This much should be possible

userRef.where('location.lat', '>=', 51.400).where('location.lat', '<=', 52.000);

Though I don't think you can chain more .where on it if it's not on the same field.

You could try to do a similar query for location.lng beneath it and then compare and match the users from both queries. Or check if the location.lng is in the desired range in your code and filter out those users. In any case you'll end up getting more results from the database than preferred and then discarding some.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Bart
  • 498
  • 2
  • 8
  • 4
    Thank you for your suggestion. I guess that's the way I am going to do it. 2 queries and then take matching results from both. Google Firebase is getting more and more disappointing with every issue I face. – Paul Strupeikis Nov 08 '17 at 18:08
  • I feel the same way about Firestore. On the surface it's been a huge improvement over Firebase, but if you want to perform more complicated queries in a deeply nested database it become a mess. – Bart Nov 09 '17 at 07:47
0

Maybe a solution for this is to have a cloud function that adds a lat_range and a lon_range field to each document as it comes into Firebase? You'll need to have predefined ranges though - so you know what you can query.

giodamelio
  • 5,465
  • 14
  • 44
  • 72