Sqlite on Android: How to create a sqlite dist db

2019-01-17 09:17发布

We are building an Android App that will use user's current location (lat, long) and show top 50 venues around the current location, sorted by distance.

We have these venues stored in an SQLite DB. We plan to ship with the sqlite DB with the app.

In order to fetch only the relevant top 50 closest venues, we want to define a db function DIST (to calculate distance between two points) and use it in our query.

How can I define a custom SQLite function for Android Apps? What will be the Java API call to do this?

We have successfully implemented this approach in our iPhone App - using Objective C.

4条回答
男人必须洒脱
2楼-- · 2019-01-17 09:23

A workaround might be to fetch all records where one of the values (say, longitude) is close to the current location. If you use this column as an index then fetching these will be very fast.

Then, you have a much reduced subset to iterate over comparing the latitudes and doing your full distance calculations.

查看更多
Luminary・发光体
3楼-- · 2019-01-17 09:35

It can be done but you cannot load this into the database from the Java API. You will need to provide your own implementation of the sqlite library that is extended to provide the functions you wish at the C level. This is not fun but it works well. Be aware that you may have issues with Android devices using non-standard architectures.

查看更多
走好不送
4楼-- · 2019-01-17 09:36

I know this is an old question, but there is a little bit easier solution I think.

This is an example, but it fails when crossing 0 degrees, although you could shift all the latitude/longitudes to adjust.

The overall solution works pretty well for ordering, but just uses the Pythagorean theorem to calculate the relative distance (note: no square root function in sqlite, but that is not relevant).

 String calcDistance = "( ( (abs(" + cLat + ")  - " + Math.abs(lat) + ") * (abs(" + cLat + ")  - " + Math.abs(lat) + ") )" +
                    "+   ( (abs(" + cLng + ") - " + Math.abs(lng) + ") * (abs(" + cLng + ") - " + Math.abs(lng) + ") ) ) as calc_distance";

If you needed to fix this distance, you would want to adjust by adding 90 to all latitudes and 180 to all longitude. Then you could get rid of that nasty abs functions.

查看更多
We Are One
5楼-- · 2019-01-17 09:41
登录 后发表回答