Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 736
Paulo Rodrigues Avatar asked Apr 12 '12 15:04

Paulo Rodrigues


1 Answers

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.

like image 55
njzk2 Avatar answered Oct 17 '22 20:10

njzk2