Sort array by distance near user location from firebase

自古美人都是妖i 提交于 2019-11-29 08:59:16

This is a complex process, requiring multiple steps. I'll try to explain the steps, but you'll have to do quite some work to turn it into a functioning solution.

Geocoding

First up: an address string like the one you have is not a location. There is no way for a computer to compare two of such strings and reliably know how far apart they are.

So the first thing you'll have to do is to turn the addresses into a more reliable indication of a location, i.e. into a latitude and longitude (a.k.a. lat/lon). The process of turning an address into lat/lon is known as geocoding. It is not really an exact science, but there are plenty of services that are quite good at this geocoding bit.

At the end of this geocoding process you will have a lat/lon combination for each address. That puts the problem back into mathematics, which is a much more exact science.

Geoqueries

Next up you'll need to compare the lat/lon of each address and calculate the distance between them. This is a relatively exact science, if you're willing to ignore inaccuracies near the poles and things like that.

Unfortunately the Firebase Realtime Database can natively only order/filter on a single property. Since a location consists of two properties (latitude and longitude) it can't filter on location without some magic.

Luckily somebody came up with a way to translate lat/lon information into a single string, known as a geohash. For example: the Google office in San Francisco is at lat/lon 37.7900515,-122.3923805, which translate to geohash 9q8yyz. The Googleplex in Mountain View is at lat/lon 37.4219999,-122.0862515, which translates to geohash 9q9hvu.

Unlike the addresses you started with, geohashes are very nicely comparable. To quote the (linked) wikipedia explanation:

nearby places [have] similar prefixes. The longer a shared prefix is, the closer the two places are.

In our two examples above, you can see the the two locations are relatively close to each other because they both start with 9q

There is an open-source library for Firebase called GeoFire that:

  1. makes it easy to store locations (for which you must have the lat/lon) in Firebase as geohashes.
  2. provides querying capabilities so that you can get nodes that are within maximum distance of a location you specify.

I recommend that you check out the iOS version of GeoFire.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!