来自当前位置的半径内的核心数据的对象基于对象的纬度和经度

时间:2014-04-24 13:09:19

标签: objective-c core-data nspredicate latitude-longitude nsfetchrequest

我希望得到距离我某个位置5公里范围内的所有物体。目前我有以下内容:

_searchDistance = 2.50;

    AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;


    float minLat = appDelegate.latitude - (_searchDistance / 69);
    float maxLat = appDelegate.latitude + (_searchDistance / 69);
    float minLon = appDelegate.longitude - _searchDistance / fabs(cos(appDelegate.longitude / 180.0 * M_PI)*69);
    float maxLon = appDelegate.longitude + _searchDistance / fabs(cos(appDelegate.longitude / 180.0 * M_PI)*69);

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription
                                   entityForName:@"Relation" inManagedObjectContext:context];
    [fetchRequest setEntity:entity];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"rel_latitude <= %f AND rel_latitude >= %f AND rel_longitude <= %f AND rel_longitude >= %f", maxLat, minLat, maxLon, minLon];
    [fetchRequest setPredicate:predicate];
    NSSortDescriptor *sort = [[NSSortDescriptor alloc]
                              initWithKey:@"rel_name" ascending:YES selector:@selector(caseInsensitiveCompare:)];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sort,nil]];

    NSArray *matches = [context executeFetchRequest:fetchRequest error:nil];

这段代码基于以下stackoverflow question

但这会在当前位置创建一个方形。这导致返回错误的值。那么请有人帮帮我吗?

1 个答案:

答案 0 :(得分:0)

正如马丁所说,只是继续削减结果。

NSMutableArray *filtered = [NSMutableArray array];
for (Relation *object in matches) {
  float lonDelta = object.rel_longitude.floatValue -centerLon;
  float latDelta = object.rel_latitude.floatValue - centerLat;
  if (radius*radius <= lonDelta*lonDelta + latDelta*latDelta) {
     [filtered addObject:object];
  }
}

请注意,这是一个(通常是足够的)近似,假设地球是一个平面。