iphone – 使用Core Data查找最近的lat / long

我有一个带有核心数据数据库的iPhone应用程序,其中包含一个位置列表,每个位置都有纬度/经度坐标.我该如何搜索距离我当前位置最近的10?

我是Core Data的新手,所以我的问题是如何进行查找,我知道如何获取当前位置等.我相信我需要设置一个带有查询字词的NSPredicate,但不确定应该如何编写.

谢谢,
Ĵ

最佳答案
你可以试试这个(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
            }
        }   
    }

转载注明原文:iphone – 使用Core Data查找最近的lat / long - 代码日志