我的问题基于CLLocationManager
并过滤某个半径范围内的位置。
我有什么:
CLLocationManager
),我的要求是我需要过滤掉用户指定位置半径100公里范围内的商店。
此外,如果在100公里范围内有超过25家商店,那么逻辑需要转移到过滤掉我所在位置的25家最近的商店。
最好的方法是什么?
答案 0 :(得分:2)
最好的选择是使用许多数据库的内置功能来为您进行过滤和排序。
基本实现非常明显:只需对商店进行排序,然后获得位于定义区域内的前25个。
以下是我可能会编写它的优化版本,因为您可能拥有数千个商店:
NSArray *stores = ...;
CLLocation *myLocation = ...;
NSMutableArray *nearestStores = [NSMutableArray array];
CLRegion *nearest100kmRegion = [CLRegion initCircularRegionWithCenter:[myLocation coordinate]
radius:100000
identifier:@"someIdentifier"];
// We will need to enumerate all stores to ensure that there are no more
// than 25 objects within the defined region.
//
// Since there may be thousands of objects and many of them can be
// out of the defined region, we should perform concurrent enumeration
// for performance reasons.
dispatch_semaphore s = dispatch_semaphore_create(1);
[stores enumerateObjectsWithOptions:NSEnumerationConcurrent
usingBlock:^(id store, NSUInteger idx, BOOL *stop)
{
if ([nearest100kmRegion containsCoordinate:[[store location] coordinate]])
{
dispatch_semaphore_wait(s, DISPATCH_FOREVER);
[nearestStores addObject:store];
dispatch_semaphore_signal(s);
}
}];
dispatch_release(s);
if ([nearestStores count] > 25)
{
[nearestStores sortWithOptions:NSSortConcurrent
usingComparator:^(id store1, id store2)
{
return [myLocation distanceFromLocation:[store1 location]] - [myLocation distanceFromLocation:[store2 location]];
}];
}
return [nearestStores subarrayWithRange:NSMakeRange(0, MAX([nearestStores count], 25))];
答案 1 :(得分:0)
请参阅Calculate distance between two latitude-longitude points? (Haversine formula)以确定2个纬度/长度对之间的距离,然后执行此操作:
按照与用户的距离对商店数组进行排序,并循环遍历数组以填充结果集。结果集计数为25或距离大于100km时停止。
如果存储数组真的比你应该首先使用100km以内的存储填充一个数组,那么如果count&lt; = 25则返回整个列表,否则排序并返回排序数组中的前25个。< / p>