Claudio
Claudio

Reputation: 2037

IPhone - SQLite distance by Latitude and Longitude

I have a embedded database in my app that has all Latitude and Longitude of some interested points and I need to know my distance from these points(get my position using GPS). My problem is: I've just figured out that SQLite can't calculate distance using the query that I have because it doesn't calculate trigonometry functions(SIN, COS...). I was trying to avoid calculating these distances programatically using this query:

NSLog(@"SELECT ((ACOS(SIN(%@ * PI() / 180) * SIN(lat * PI() / 180) + COS(%@ * PI() / 180) * COS(lat * PI() / 180) * COS((%@ – lon) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) AS `distance` FROM `members` HAVING `distance`<=’1000′ ORDER BY `distance`", Latitude,Latitude, Longitude);

Does anybody has a solution?

Regards!

Upvotes: 6

Views: 3921

Answers (2)

Monolo
Monolo

Reputation: 18253

Yeah, you can make a simple query based on a rectangle around the location, then use the haversine formula to compute the exact distance.

The advantage of that is that you get to use indexes on the SQLite table.

More about the haversine formula: http://en.wikipedia.org/wiki/Haversine_formula

Upvotes: 0

Jeroen Coup&#233;
Jeroen Coup&#233;

Reputation: 1404

Do it in Objective C.

this guy had the same problem: http://www.thismuchiknow.co.uk/?p=71

Upvotes: 9

Related Questions