Find closest by lat / long with Core Data

I have an iPhone app with a Core Data database containing a list of locations, each with lat / long coordinates. How can I find the nearest 10 to my current location?

I'm new to Core Data, so my question is really how to do a search, I know how to get my current location, etc. I believe that I need to configure NSPredicate with the query condition, but I don’t know exactly how to make it write.

Thanks J

+4
source share
3 answers

You can try this ( link )

double M_PI = 3.141592653589793; #define d2r (M_PI / 180.0) double haversine_km(double lat1, double long1, double lat2, double long2) { double dlong = (long2 - long1) * d2r; double dlat = (lat2 - lat1) * d2r; double a = pow(sin(dlat/2.0), 2) + cos(lat1*d2r) * cos(lat2*d2r) * pow(sin(dlong/2.0), 2); double c = 2 * atan2(sqrt(a), sqrt(1-a)); double distance = 6367 * c; return distance; } - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { /*Calculate distance of all locations in DB and current location. If diff. between any stop is less than x meters, perform desired operation*/ NSArray *listLocationsFromDB = [self getLocations]; //Get all locations from DB for (Location *location in listLocationsFromDB) { double distance = haversine_km(newLocation.coordinate.latitude, newLocation.coordinate.longitude, [location.latitude doubleValue], [location.longitude doubleValue]); distance *= 1000; if (distance <= 200) { //200 meters //Your code here } } } 
+5
source

There is also a CoreLocation function that solves this problem:

 - (CLLocationDistance)getDistanceFrom:(const CLLocation *)location 
+8
source

You need a Haversin formula for the distance between lat / long pairs. You can have a calculated field for each object that returns its distance from a given point, and then it is ordered by this distance to get the closest β†’ farthest.

See this Haversine article

And here is the version of Objective-c ...

Objective-c Haversine

+4
source

All Articles