gpt4 book ai didi

ios - 如何根据从纬度和经度计算出的距离对数组进行排序。

转载 作者:行者123 更新时间:2023-11-28 21:25:42 25 4
gpt4 key购买 nike

我有一个自定义对象数组。并且对象具有包括纬度和经度的参数。我想根据它们与当前位置的距离对该数组进行排序。我可以获得当前位置和每个对象之间的距离。但我不知道如何在计算距离后对其进行排序。例如:

MainArray = [{name:NYC, lat:1.11, lng:2.22}, {name:CAL, lat:3.33, lng:4.44}, {name:LA, lat:5.55, lng:6.66}].

假设我位于三个位置的中心,然后我想按附近的顺序对它们进行排序。对不起,如果上面的语法有误,我无法发布原始数据,因为它太大了。

我怎样才能做到这一点?请帮忙。

最佳答案

几乎与之前的答案相同,但没有添加字段:

CLLocation *yourLocation = [[CLLocation alloc] initWithLatitude:.... longitude:...];
NSArray *array = @[@{ @"name": @"NYC", @"lat": @1.11, @"lng": @2.22}, @{@"name":@"CAL", @"lat":@3.33, @"lng":@4.44}, @{@"name":@"LA", @"lat":@5.55, @"lng":@6.66}];
array = [array sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *obj1, NSDictionary *obj2) {
CLLocation *location1 = [[CLLocation alloc] initWithLatitude:[obj1[@"lat"] double] longitude:[obj1[@"lng"] double]];
CLLocation *location2 = [[CLLocation alloc] initWithLatitude:[obj2[@"lat"] double] longitude:[obj2[@"lng"] double]];

CLLocationDistance distance1 = [location1 distanceFromLocation:yourLocation];
CLLocationDistance distance2 = [location2 distanceFromLocation:yourLocation];

if (distance1 > distance2) {
return (NSComparisonResult)NSOrderedDescending;
}

if (distance1 < obj2 distance2) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}];

关于ios - 如何根据从纬度和经度计算出的距离对数组进行排序。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38195990/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com