如何排序最近距离的对象数组(经度,纬度)? [英] How to sort array of objects(latitude, longitude) by nearest distance?

查看:249
本文介绍了如何排序最近距离的对象数组(经度,纬度)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经从核心数据数组,我试图想我怎么可以在最近距离对数组进行排序:

 的for(int i = 0; I< allTask​​s.count;我++){
        ID singleTask = allTask​​s [I]
        双纬度= [singleTask [@纬度]的doubleValue];
        双经度= [singleTask [@经度]的doubleValue];
    }

编辑:
当前位置和阵列中的所有位置之间的距离。
我知道如何计算距离,我不知道如何对它们进行排序。


解决方案

  1. 得到您的currentPosition的CLLocation(这是通过CLLocationManager完成)


  2. 计算每个项目,并保存距离+项目在字典一对距离


  3. 排序字典allKeys阵列比较:选择


所以

  CLLocation *电流= ...;
*的NSMutableDictionary distsAndTasks [字典的NSMutableDictionary];对(在allTask​​s ID任务){
    CLLocation * taskLoc = [[CLLocation页头] initWithLatitude:task.lat经度:task.long]; //!
    CLLocationDistance DIST = [taskLoc distanceFrom:当前];
    如果(distsAndTasks [@(DIST)]){
        NSMutableArray里* equidstants = [distsAndTasks [@(DIST)mutableCopy]
        [equidstants ADDOBJECT:任务];
        distsAndTasks [@(DIST)] = equidstants;
    }
    其他{
        distsAndTasks [@(DIST)] = @ [任务];
    }
}NSArray的* sortedDists = [distsAndTasks.allKeys sortedArrayUsingSelector @选择器(比较:)//任务现在可以在一个有序的方式访问
对(在sortedDists的NSNumber * DIST){
    NSArray的* tasksAtDistance = distsAndTasks [测距]
    的NSLog(@%@,tasksAtDistance);
}

I've an array from core data and I'm trying to think how can I sort the array by the nearest distance:

for (int i=0; i<allTasks.count; i++) {
        id singleTask = allTasks[i];
        double latitude = [singleTask[@"latitude"] doubleValue];
        double longitude = [singleTask[@"longitude"] doubleValue];
    }

EDIT: The distance between current location and all the locations in the array. I know how to calculate the distance, I don't know how to sort them.

解决方案

  1. get the CLLocation for your currentPosition (this is done via CLLocationManager)

  2. calculate the distances for each item and store distance+item as a Pair in a Dictionary

  3. Sort Dictionary allKeys array with compare: selector

so

CLLocation *current = ...;
NSMutableDictionary *distsAndTasks [NSMutableDictionary dictionary];

for(id task in allTasks) {
    CLLocation *taskLoc = [[CLLocation alloc] initWithLatitude:task.lat longitude:task.long];//!
    CLLocationDistance dist = [taskLoc distanceFrom:current];
    if(distsAndTasks[@(dist)]) {
        NSMutableArray *equidstants = [distsAndTasks[@(dist)] mutableCopy];
        [equidstants addObject:task]; 
        distsAndTasks[@(dist)] = equidstants; 
    }
    else {
        distsAndTasks[@(dist)] = @[task]; 
    }
}

NSArray *sortedDists = [distsAndTasks.allKeys sortedArrayUsingSelector@selector(compare:)

//the tasks can now be access in a sorted way
for(NSNumber *dist in sortedDists) {
    NSArray *tasksAtDistance = distsAndTasks[dist];
    NSLog(@"%@", tasksAtDistance);
}

这篇关于如何排序最近距离的对象数组(经度,纬度)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆