Reputation: 564
I have records in my Core Data store with latitude and longitude properties. Now I need to find the record that is closest to a given location. In SQL I would do it like:
select t.lat
,t.lon
,(t.lat-varLat) + (t.lon - varLon) diff
from table t
order by diff ASC.
given varLat and varLon are the coordinates of the location I want the closest record to. However I have no clue how to do this in Core Data with an NSPredicate.
The worst thing I can imagine is looping fetchrequests with a predicate that expands a 'search range' around the given (varLat,varLon), and using
longitude BETWEEN %@ && latitude BETWEEN %@
with 2 arrays (each having center+ and center- radius as array members) as parameters, each time expanding this range until I get a hit.. however, this is far from optimal.
Thanks for your advice.
Upvotes: 0
Views: 126
Reputation: 80273
First, your query is not correct, with an error of up to app. 40%. Your calculation just sums up the lat and long differences. The actual difference, assuming a 2D surface, is sqrt((lat-varlat)^2 + (lon-varLon)^2)
. On the actual surface the geometry is more complicated, but the difference negligible in most cases.
In Core Data it is not uncommon to fetch all instances and then iterate through them in a loop. The reason is that Core Data uses a mechanism called faulting that will allow you to retrieve a large number of objects without too much memory overhead.
Upvotes: 2