2

Is it possible to query data from Firestore sort by distance? Here is an example: I have position of user1 and user2 in latitude&longitude and user1 will query data from user2 if he is not further away than 5 kilometers.

Here is a code I tried but I got a problem because Firebase can't query on different fields.

I need position in latitude and longitude to valid that users aren't further away than 5 kilometers.

  function querying(ref){
      var currentLoc=[0,0]; //current location(latitude&lontitude)
      var input = 10;       //input distance in kilometers Here is an example i use 10 kilometers
      var d=(input)/100;    //convert input in kilometers to distance
      ref.where("position.lat","<=",currentLoc[0]+d).where("position.lat",">=",currentLoc[0]-d)
         .where("position.lon","<=",currentLoc[1]+d).where("position.lon",">=",currentLoc[1]-d)
         .get().then((snapshot)=>{
            snapshot.forEach((doc)=>{
              console.log(doc.id,"=",doc.data());
            });
          }).catch((error)=>{
            console.log("error",error);
       });
    }
Supagon Srisawas
  • 113
  • 1
  • 1
  • 9
  • Welcome to SO. Yes, this is possible. However asking 'is this possible' isn't really asking a specific coding question so it's unlikely you're going to get an answer that will help. Please review the following two guides on asking questions: [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) and [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) – Jay Oct 20 '18 at 13:01
  • I'm sorry for my English skill now i edited my post. so my question is How to query data 'sort by distance' without querying whole data? using firebase – Supagon Srisawas Oct 20 '18 at 13:12
  • 1
    We understand what you are asking but the answer will depend on what codebase you're using, what your existing structure looks like and also, and most importantly *what code you've tried*. This is not a code writing service but we are here to help with existing code. So please review the two guides I linked above. They are available in other languages as well. – Jay Oct 20 '18 at 13:23
  • yeah i tried in java script and i keep my data in Firestore in map variable but it display an error – Supagon Srisawas Oct 21 '18 at 09:03

0 Answers0