views:

53

answers:

2

I need to identify items of interest nearby to a particular latitude/longitude. I have two sets of objects stored in Core Data:

PostalArea
- latitude
- longitude
- postcode

Store
- name 
- latitude
- longitude

I need to be able to retrieve a record from the PostalArea table, and then find stores which are closeby.

Most of the examples I've found are SQL based. I'm hoping someone can assist me with getting this working with Core Data. Ideally I would like to limit the result set to a certain number (say, 10), as opposed to limiting it based on distance.

EDIT: pulling all the records into memory is an option, if need be.

A: 

How would you feel about a REST service option? Is you use the Google APIs, you can query for exactly those things. There are plenty of JSON interfaces available for Objective C.

Charlie Martin
Thanks, but REST is not an option. This needs to work offline.
alku83
+1  A: 

The most common solution to this is to determine a min/max of both lat and long and then do a predicate based on those. That would narrow your search to within a circle and then with those remaining objects in memory you can sort by closest to the point.

Update

Once you have the objects in memory you can then do some fun things with them. For instance you could have a transient value called 'currentPoint' and you could then KVO on the resulting array such as:

[resultingArray setValue:aPoint forKey:@"currentPoint"];

Then you could have a method that returns the distance from that point which you can sort by.

That is one example, I am sure there are other ways but the general idea is to get a subset of locations into memory so that you can then calculate distance and finally sort.

Marcus S. Zarra
Fair enough, but how would I go about sorting by closing to the point? I think that's actually the answer I am seeking :)
alku83
Updated answer.
Marcus S. Zarra
Sorry, guess I'm not being that clear - I need to create the method for calculating the distance.
alku83
That was not your original question. Creating the method to determine the distance between two coordinates is already [answered several times on SO](http://stackoverflow.com/questions/27928/how-do-i-calculate-distance-between-two-latitude-longitude-points).
Marcus S. Zarra
I think it was - I said I need to be able to retrieve a record from the table, and find stores nearby. I was hoping to be able to do that without pulling all the records into memory, but will if I have to.
alku83
You do not need to pull all of the records into memory. You can pull in a subset into memory based on a distance. Calculate a min/max lat/long and filter on that. It will then give you everything within that range (i.e. everything within 10 miles of the point).
Marcus S. Zarra
Ok, fair enough. Thanks for your help.
alku83