Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone geo radius search; Use Core Data or SQLite?

I am writing an application which has ca. 7000 european restaurants in the database and I want to show a list of the nearest ones to the user, for example all of them which are in a radius of 5km to the user.

I could do the search on the server but it then requires internet. Is it possible to save the data on the iPhone and query the database? I can't find any references for something like that in core data or iPhones SQLite.

Do I really need to program it myself with Pythagoras and stuff and calculate the distance to every restaurant on every query? Or is there some other way?

[update] I'd like to use it like I do already on the server (but to do it on the iPhone): SELECT * FROM restaurants WHERE ST_Distance_Sphere(geo, ST_GeomFromText(POINT(55.98767 57.12345), -1)) < 5000

I want the user to be able to find a restaurant even if she has no internet connection, for example when you're in a foreign country.

like image 999
Jeena Avatar asked Jul 14 '11 09:07

Jeena


1 Answers

Read up on latitude and longitude calculations. Latitude an longitude are themselves distances expressed as arcs upon a spherical surface. If you have a database of locations expressed by latitude and longitude, then you can perform a fetch to find only those records that fall within a few degrees latitude north and south and a few degrees longitude east and west of the users current location.

So you would end up with a predicate that would be something like (psuedo-code):

latitude >= (currentLatitude-aFewMinutesOfArc)
AND
latitude <= (currentLatitude+aFewMinutesOfArc)
AND
longitude >= (currentLongitude-aFewMinutesOfArc)
AND
longitude >= (currentLongitude+aFewMinutesOfArc)

... this would create a logical box which would return all restaurant records that fell within the box. Then if you needed to calculate the exact distances you would only have to perform calculation on a handful of records out of the 7,000 you have.

I would recommend reading up on Location Services because it provides a lot of tools for handling location calculations.

As to whether to use plain SQL or Core Data, check out this previous answer on the subject. In brief, if you already know the C SQL api and your data is simple, large and static, then SQL is a good choice. If you can take time to learn Core Data and your data is complex and dynamic, then Core Data is the better choice regardless of the size of the data.

like image 154
TechZen Avatar answered Nov 15 '22 00:11

TechZen