查找距离阵列最近的位置(iOS)

问题描述:

我需要从NSMutableArray中找到20个存储CLLocationCoordinate2D对象的壁橱存储并将其添加到另一个阵列中。查找距离阵列最近的位置(iOS)

任何想法,我该怎么做? 谢谢!

如何使用distanceFromLocation:?按距离对数组进行排序,取第一个元素。

PS:我假设你实际存储CLLocation实例,因为CLLocationCoordinate2Dstruct,而不是引用类型。如果您真的设法将非对象存​​储在NSArray中,则可以轻松地从经度和纬度构造CLLocation对象。

编辑

简单快捷的例子

var a = [CLLocation]() // this would be your actual array 
let loc = CLLocation() // this would be your current location 
a.sortInPlace { (l1, l2) -> Bool in 
    l1.distanceFromLocation(loc) <= l2.distanceFromLocation(loc) 
} 
let smallest = a.first? // this would be your closest value. 

在Objective-C,相关的方法是sortUsingComparator:NSMutableArray像这样:

NSMutableArray* a = [NSMutableArray new]; 
CLLocation* loc = [CLLocation new]; 
[a sortUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) { 
// Edit 3: verbose comparator. 
    float dist1 =[(CLLocation*)obj1 distanceFromLocation:loc]; 
    float dist2 = [(CLLocation*)obj2 distanceFromLocation:loc]; 
    if (dist1 == dist2) { 
     return NSOrderedSame; 
    } 
    else if (dist1 < dist2) { 
     return NSOrderedAscending; 
    } 
    else { 
     return NSOrderedDescending; 
    } 
}]; 

// Edit 2 
CLLocation* smallest = a.firstObject; 
    NSMutableArray* closest = [NSMutableArray new]; 
for (int i = 0; i < 20; i++) { 
    [closest addObject:a[i]]; 
} 
+0

你能给我一个代码示例为了这? 顺便说一句,我存储在一个名为'Store'的自定义类(从'NSObject'继承)中有一个地址('NSString'),名称('NSString')和geoPoint('CLLocationCoordinate2D')。 – Yhper

+0

客观C :)) – Yhper

+0

你去了:) – SmokeDispenser