Android sqlite sort on calculated column (co-ordinates distance)

╄→尐↘猪︶ㄣ 提交于 2019-11-29 00:30:39

This won't completely help, but for situations like this, seriously consider using rawQuery() instead of query(), so you can pass in a full SQL statement vs. having to chop it into pieces.


Your bigger problem is that I don't see that SQLite has trigonometric functions.

You do not indicate how you are using the Cursor you are getting back from your query. For example, if you are putting the Cursor into some sort of CursorAdapter, you could:

  • convert the Cursor into an ArrayList<Position>, where Position is some Java class you define with your data
  • close the Cursor, to release the RAM it takes up
  • sort the ArrayList<Position> using Arrays.sort()
  • wrap the ArrayList<Position> in an ArrayAdapter<Position> and use that where you had been using your CursorAdapter

yeah, that works perfectly.

it can be made into a stored procedure like so:

http://www.thismuchiknow.co.uk/?p=71 [Distance function for sqlite]

there's also the Perst spatial database for android which is excellent, and the SpatiaLite spatial database which is also awesome, which you could link to in your app.

w/out using a specialized lib, you could approximate the distance a few ways (calculate it just as if it were planar (rectangular) then use the Haversine formula to sort the subset later, use a lookup table that approximates cos, sin, etc, group locations into 5 sq. mile zones and search neighboring cells up to the max, etc...)

In my app BostonBusMap I used an approximation to speed up the calculation of closest objects to a point. You can scale the longitude by cos(latitude) and then just use the Pythagorean formula to calculate a sorting distance (omitting the square route since it's not necessary for a comparison distance). It works reasonably well for small distances.

Source: http://en.wikipedia.org/wiki/Geographical_distance#Spherical_Earth_projected_to_a_plane

I've just written an app that needs to sort a set of coordinates based on distance. What I did was create an array of IDs and Distances and then sorted them within Java. Then I could find the nearest locations and select them from the Database. Of course this approach may not work for you depending on how many points you have and how you access the database. This worked fine for ~350 points, in my Nando's Finder app.

Additionally I used Location.distanceBetween(..) from the SDK to calculate the distances for me. I would hope this method would be implemented in C to ensure it is fast, however, a quick look at the SDK source shows it is written in Java :(.

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