5

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

I'm new to Core Data so my question is really how to do the lookup, I know how to get my current location etc. I believe I need to setup an NSPredicate with a query term but not sure exactly how that should be written.

Thanks, J

JWood
  • 2,804
  • 2
  • 39
  • 64
  • Here's my similar question. The short answer is that you can't find the nearest without loading all objects, then checking each one, but you can make it more efficient with bounding boxes. http://stackoverflow.com/questions/2176127/core-data-and-core-location – nevan king Oct 20 '11 at 12:33

3 Answers3

8

There is also a CoreLocation function which solves that particular issue :

- (CLLocationDistance)getDistanceFrom:(const CLLocation *)location
Alexis C.
  • 4,898
  • 1
  • 31
  • 43
5

You may try this (reference)

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
            }
        }   
    }
Sahil Khanna
  • 4,262
  • 8
  • 47
  • 72
4

You need the Haversine formula for distance between lat / long pairs. You can have a calculated field for each object which returns it's distance from a set point, then order by this distance to get the nearest -> farthest.

See this article on Haversine

And here is an Objective-c version...

Objective-c Haversine

Simon Lee
  • 22,304
  • 4
  • 41
  • 45