Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase query nearby object

Tags:

firebase

In mysql, I was using haversine formula to query nearby object.

Using this formula Formula

SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance 
FROM markers HAVING distance < 25 ORDER BY distance LIMIT 0 , 20;

Which

  • 3959: radius of earth in miles
  • 37,-122 : given lat lng
  • 25: within 25 miles

In Firebase, Can I store the users lat lng like what I did in mysql? Create a marker table. id, lat, lng columns and then use the formula to query

Updated

I should ask, what is the way to query nearby using this formula in firebase.

like image 219
vzhen Avatar asked Dec 16 '22 10:12

vzhen


1 Answers

Short answer, not like you want it to.

Firebase essentially has two ways to query for data: by path and by priority. This is more limited than SQL, and there's a very good reason for that — our API is carefully designed to only allow operations we can guarantee to be fast. Firebase is a real-time and scalable backend, and we want to enable you to build great apps that can serve millions of users without compromising on responsiveness.

See, what is firebase and deNormalizing data Also, this SO question is similar.

Response to comment: Firebase will not calculate the sin( radians(X) ) for you. That's a 'slow' operation. So, you would need to store that information into the data when you save it. I'm not 100% certain, but you could store the markers and the also store the longitude/latitude in a separate parent.

Root
    -> Markers
    -> longitude (Use the value as priority) -> MarkerId
    -> latitude (Use the value as priority) -> MarkerId

Then you should be able to use bounding to find the Max and Min longitude and latitude. Use that to query the longitude and latitude paths by priority. If a MarkerId exists in both, you use it.

A quick bit of research found this article on Latitude Longitude Bounding Coordinates

like image 114
SH- Avatar answered Jan 25 '23 23:01

SH-