0

Kindly help me write this function I have this list where each driver is listed with 1 current latitude longitude 2 onDuty or not 3 vehicle type 4 driver details

whenever user initiates search function searches for 1 vehicel type user has chosen 2 AND if driver is on duty 3 AND if driver is within 10 km radius (using latitude and longitude)

and copy all eligible drivers to -> availableDriverListenter image description here

distance calculating code

function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
  var R = 6371; // Radius of the earth in km
  var dLat = deg2rad(lat2-lat1);  // deg2rad below
  var dLon = deg2rad(lon2-lon1); 
  var a = 
    Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * 
    Math.sin(dLon/2) * Math.sin(dLon/2)
    ; 
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
  var d = R * c; // Distance in km
  return d;
}

function deg2rad(deg) {
  return deg * (Math.PI/180)
}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Roy Sougat
  • 83
  • 7
  • The Firebase Realtime Database and Cloud Firestore are two separate databases. Please only mark your question with the relevant tag, not with both. – Frank van Puffelen Jul 30 '21 at 14:18
  • Yes it helped, knowing the limitations of fb rt db helped, my application demanded some extra search and filteration, any ways got it with some tweaking – Roy Sougat Aug 10 '21 at 04:14
  • Perfect. I also just added this link to my answer, which I somehow forgot last week: https://www.youtube.com/watch?v=mx1mMdHBi5Q – Frank van Puffelen Aug 10 '21 at 13:45

1 Answers1

1

Searching for a radius around a point requires that you perform a range comparison on the longitude and the latitude of each document. In a Firestore query you can only perform a range comparison on a single field, so with your current data structure you cannot perform the query you want.

There is a way to encode longitude and latitude into a single value that can be used for such comparisons, known as a Geohash. If you add a Geohash to each document, you can then perform the query. To learn how to do this, have a look at the Firestore documentation on performing Geoqueries.

I also recommend reading: Query for nearby locations. While for a different database, the limits and thus solution are the same. If you got the time, I also recommend watching this talk I gave a few years ago about how to add geoqueries to Firestore.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807