查找距离阵列最近的位置(iOS)
问题描述:
我需要从NSMutableArray
中找到20个存储CLLocationCoordinate2D
对象的壁橱存储并将其添加到另一个阵列中。查找距离阵列最近的位置(iOS)
任何想法,我该怎么做? 谢谢!
答
如何使用distanceFromLocation:
?按距离对数组进行排序,取第一个元素。
PS:我假设你实际存储CLLocation
实例,因为CLLocationCoordinate2D
是struct
,而不是引用类型。如果您真的设法将非对象存储在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]];
}
你能给我一个代码示例为了这? 顺便说一句,我存储在一个名为'Store'的自定义类(从'NSObject'继承)中有一个地址('NSString'),名称('NSString')和geoPoint('CLLocationCoordinate2D')。 – Yhper
客观C :)) – Yhper
你去了:) – SmokeDispenser