Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
495 views
in Technique[技术] by (71.8m points)

android - Calculate distance between two points directly in SQLite

In my web/MySQL application I have something like this to get distance between two points:

6371 * acos(cos(radians(-19.83996)) * cos(radians(lat)) * cos(radians(-43.94910) - radians(lng)) + sin(radians(-19.83996)) * sin(radians(lat)))

But I tested in SQLite and these mathematical functions (acos, cos, radians, sin) do not exist. Is there something equivalent for me to calculate the distance directly in the database?

However, I have an iPhone application that uses this method to calculate. Works perfectly, but now I need to perform this same search in the database in an Android application.

Thanks in advance.

UPDATE

I have 9000 points to calculate distance and obtain the 5 nearby locations of a given point.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is what I would do:

Take your given point. Measure a (that is an arbitrary value to be refined) ~2km wide square around it and take the values for the east/west/north/south bounds.

Make a query for elements inside this square. This one is easy, you just have to

select * from points where lat between ? and ? and lon between ? and ?

Count your result. Not enough result (less than 5, obviously, but I would say twice that to be sure), retry with a larger radius. Too much (say, more than 100), try again with a smaller radius.

Once you have enough, load them, make sure all 5 elements you need are not only in the Xkm wide square, but also in the Xkm radius circle (to avoid having a potential closer element not detected by the previous approximation).

Another approach

Valid only if your given point is relatively close to those you are searching.

Measure a local approximation of a flat earth. Close to your point, you can consider a linear relation between lat, lon, and distance. That allows you to make a request sorted by a simple calculus. (multiplication and addition). Again, select a little more points in order to make the proper calculation after the SQLite request.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...