我正在通过JSON获得价值观:
{
id = 1;
latitude = "-23.0002";
longitude = "-43.2438";
name = Vips;
}
{
id = 2;
latitude = "-22.9283";
longitude = "-43.1746";
name = Elegance;
}
...
我需要在tableview中显示这些值,按距离到用户位置排序。并且必须始终更新此值。我怎么能这样做?
displayObject是一个NSMutableArray,我从WS中获取值。 在viewWillappear中,我正在尝试:
NSArray *rawData = [NSArray arrayWithArray:displayObject];
rawData = [rawData sortedArrayUsingComparator: ^(id a, id b) {
CLLocationDistance dist_a= [[a objectForKey:@"coordinate"] distanceFromLocation: locAtual];
CLLocationDistance dist_b= [[b objectForKey:@"coordinate"] distanceFromLocation: locAtual];
if ( dist_a < dist_b ) {
return (NSComparisonResult)NSOrderedDescending;
} else if ( dist_a > dist_b) {
return (NSComparisonResult)NSOrderedDescending;
} else {
return (NSComparisonResult)NSOrderedSame;
}
}];
但它不起作用。我只有纬度和经度。我没有“坐标”。 有人?
谢谢!!答案 0 :(得分:5)
如果您正在计算距离,请将其与存储在数组中的数据一起添加,然后根据距离进行排序。
for (int idx = 0; idx<[displayObject count];idx++) {
NSMutableDictionary *dict = [displayObject[idx] mutableCopy];
CLLocationDegrees latitude = [dict[@"latitude"] doubleValue];
CLLocationDegrees longitude = [dict[@"longitude"] doubleValue];
CLLocation *location = [[CLLocation alloc]initWithLatitude:latitude longitude:longitude];
CLLocationDistance distance = [userLocation distanceFromLocation:location];
//Storing as string since latitude and longitude is also string values
//Since its a dictionary storing as NSNumber is better
dict[@"distance"] = [@(distance) stringValue];
displayObject[idx] = dict;
}
//sorting based on distance
NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"distance" ascending:YES];
[displayObject sortUsingDescriptors:@[descriptor]];
答案 1 :(得分:1)
首先创建具有纬度和经度的位置对象:
CLLocation *location = [[CLLocation alloc] initWithLatitude:-23.0002 longitude:-43.2438];
CLLocation *userLocation = [[CLLocation alloc] initWithLatitude:-23.0002 longitude:-43.2438];
使用这两个对象,可以使用以下方法检查距离:
-(CLLocationDistance)distanceFromLocation:(const CLLocation *)location
例如:
CLLocationDistance dist_a = [locationUser distanceFromLocation:location];
答案 2 :(得分:1)
你的比较器错了。试试这个:
rawData = [rawData sortedArrayUsingComparator: ^(id a, id b)
{
CLLocation *locationA = [[CLLocation alloc] initWithLatitude:[[a objectForKey:@"latitude"] doubleValue] longitude:[[a objectForKey:@"longitude"] doubleValue]];
CLLocation *locationB = [[CLLocation alloc] initWithLatitude:[[b objectForKey:@"latitude"] doubleValue] longitude:[[b objectForKey:@"longitude"] doubleValue]];
CLLocationDistance dist_a = [locationA distanceFromLocation:currentLocation];
CLLocationDistance dist_b = [locationB distanceFromLocation:currentLocation];
if ( dist_a < dist_b ) {
return (NSComparisonResult)NSOrderedAscending;
} else if ( dist_a > dist_b) {
return (NSComparisonResult)NSOrderedDescending;
} else {
return (NSComparisonResult)NSOrderedSame;
}
}];