iPhone:基于位置的排序

iPhone:基于位置的排序,iphone,ios,sorting,Iphone,Ios,Sorting,我一直在开发一个iPhone应用程序,其中我有一个NSMutableArray中的用户列表,如下所示 myMutableArray: ( { FirstName = Getsy; LastName = marie; Latitude = "30.237314"; Longitude = "-92.461008"; }, { FirstName = Angel; LastName

我一直在开发一个iPhone应用程序,其中我有一个NSMutableArray中的用户列表,如下所示

myMutableArray: (
    {
        FirstName = Getsy;
        LastName = marie;
        Latitude = "30.237314";
        Longitude = "-92.461008";
    },
    {
        FirstName = Angel;
        LastName = openza;
        Latitude = "30.260329";
        Longitude = "-92.450414";
    },
    {
        FirstName = Sara;
        LastName = Hetzel;
        Latitude = "30.2584499";
        Longitude = "-92.4135357";
    }
)
我需要通过计算纬度和经度,根据我所在位置附近的位置对用户进行排序。到目前为止,我还不能做到这一点。有人能帮我拿些样品吗

更新:根据sch先生的建议,我正在尝试以下方法。请检查我的更新代码。好吗

    NSArray *orderedUsers = [myMutableArray sortedArrayUsingComparator:^(id a,id b) {
    NSArray *userA = (NSArray *)a;
    NSArray *userB = (NSArray *)b;
    CGFloat aLatitude = [[userA valueForKey:@"Latitude"] floatValue];
    CGFloat aLongitude = [[userA valueForKey:@"Longitude"] floatValue];
    CLLocation *participantALocation = [[CLLocation alloc] initWithLatitude:aLatitude longitude:aLongitude];

    CGFloat bLatitude = [[userA valueForKey:@"Latitude"] floatValue];
    CGFloat bLongitude = [[userA valueForKey:@"Longitude"] floatValue];
    CLLocation *participantBLocation = [[CLLocation alloc] initWithLatitude:bLatitude longitude:bLongitude];

    CLLocation *myLocation = [[CLLocation alloc] initWithLatitude:locationCoordinates.latitude longitude:locationCoordinates.longitude];

    CLLocationDistance distanceA = [participantALocation distanceFromLocation:myLocation];
    CLLocationDistance distanceB = [participantBLocation distanceFromLocation:myLocation];
    if (distanceA < distanceB) {
        return NSOrderedAscending;
    } else if (distanceA > distanceB) {
        return NSOrderedDescending;
    } else {
        return NSOrderedSame;
    }
}];
NSArray*orderedUsers=[myMutableArray SortedArray UsingComparator:^(id a,id b){
NSArray*userA=(NSArray*)a;
NSArray*userB=(NSArray*)b;
CGFloat aLatitude=[[userA valueForKey:@“纬度”]floatValue];
CGFloat aLongitude=[[userA valueForKey:@“经度”]floatValue];
CLLocation*ParticipantLocation=[[CLLocation alloc]initWithLatitude:纬度经度:经度];
CGFloat清晰度=[[userA valueForKey:@“纬度”]floatValue];
CGFloat bLongitude=[[userA valueForKey:@“经度”]floatValue];
CLLocation*participantBLocation=[[CLLocation alloc]initWithLatitude:清晰经度:bLongitude];
CLLocation*myLocation=[[CLLocation alloc]initWithLatitude:locationCoordinates.latitude经度:locationCoordinates.longitude];
CLLocationDistanceA=[ParticipantLocationDistanceFromLocation:myLocation];
CLLocationDistanceB=[ParticipantBlocationDistanceFromLocation:myLocation];
if(距离A<距离B){
回报率下降;
}否则如果(距离A>距离B){
退而求其次;
}否则{
返回指定名称;
}
}];

谢谢大家!

您可以计算您的位置与每个项目位置之间的距离,并按该值排序。

首先,您需要计算当前位置与每个其他用户位置之间的距离

从数学角度讲,这里有一个

现在,您可以使用“编程联盟”类,下面是一个示例:

(CLLocationDistance)getDistanceFrom:(const CLLocation *)location
但首先需要根据纬度和经度创建location对象。您可以使用:

(id)initWithLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude
NSArray*orderedUsers=[用户使用比较器进行排序:^(id a,id b){
用户*userA=(用户*)a;
User*userB=(User*)b;
CLLocationDistanceA=[userA.location getDistanceFromLocation:myLocation];
CLLocationDistanceB=[userB.location getDistanceFromLocation:myLocation];
if(距离A<距离B){
回传
}否则如果(距离A>距离B){
退而求其次;
}否则{
返回指定名称;
}
}];
-(无效)视图加载{
[超级视图下载];
//此数组是全局获取的
列出\u位置数组=[[NSMutableArray alloc]initWithObjects的\u:
@"纬度":"17.415045","逻辑度":"78.421424","纬度":"17.415045","逻辑度":"78.421424","纬度"17.415045","逻辑度":"17.415044","逻辑度"","17.415044"逻辑度
,无];
}
-(无效)排序位置数组{
//CLLocation*currentLocation=[[CLLocation alloc]initWithLatitude:[currentLatitude doubleValue]经度:[currentLogitude doubleValue]];
CLLocation*currentLocation=[[CLLocation alloc]initWithLatitude:CurrentLatitude此处经度:CurrentLogHere];
NSMutableArray*tempLocationsArr=[[NSMutableArray alloc]initWithCapacity:[locationsArray count]];
for(int i=0;i distB){
退而求其次;
}否则{
返回指定名称;
}
}];
//ArrayAfterSorting是另一个存储排序数据的可变数组
[ArrayAfterSorting removeAllObjects];
[SortLocationary Enumerative ObjectsUsingBlock:^(CLLocation*location,整数idx,布尔*stop){
NSMutableDictionary*tempDict=[[NSMutableDictionary alloc]init];
[tempDict setObject:[NSString stringWithFormat:@“%f”,location.coordinate.latitude]forKey:@“latitude”];
[tempDict setObject:[NSString stringWithFormat:@“%f”,位置.坐标.经度]forKey:@“逻辑度”];
[ArrayAfterSorting addObject:tempDict];
}];
NSLog(@“sortedArray:%@”,排序后的阵列);
}
}

您好,谢谢您的回复。甚至不计算,我也想知道我如何迭代所有用户并实现这一点。非常感谢!如何遍历所有用户并将其位置与当前位置进行比较和排序?您可以使用普通的
for循环
遍历所有对象,并使用方法:[array objectAtIndex:theIndex];是的,但是迭代意味着,我需要整理一下。嘿,Getsy,看看下面我的答案。你能在你添加的代码的第一行之前验证myMutableArray是nil还是空的吗。你太棒了!非常感谢你!不,你需要用userB来表达清楚和空洞。嗨,好的..在我的例子中,(User*)a,(User*)b是什么。我有一个数据数组。a和b是两个被比较的对象。因此,您应该找到一种方法来访问每个对象中的位置,但这取决于您在数组中放置的对象的类型。好的。。我有两个问题,第一个。”getDistanceFrom只是“distanceFromLocation”吗?2.由于我有一个NSMuableArray中的数据,您认为这段代码会遍历其中的所有数组吗?(或)我必须在内部添加任何for循环?是的,你是对的。getDistanceFrom应该是distanceFromLocation。关于第二个问题,您不必进行for循环,sortedArrayUsingComparator将遍历所有项并返回一个排序数组。好的,那么这是我的问题,我有一个可变数组,如果我不能循环它(或者)像userB=[mymutablearray objectAtIndex:i]这样的东西,我如何给userB?谢谢..但我刚才给出了四个字段的示例,例如firstname、lastname、latitude和longitude。实际上,我在一个数组中有大约20个字段,大约
You may solve your problem in following way
1)Firstly store all above values in separate array Like latArray ,longArray,nameArray
2)Now get the distance between location(longArray,latArray) from your current location.
Then store these distances in separate Array(distanceArray).

//getDistance Between currentLocation and desired Location
-(void *)getDistanceFromCurrentLocation{  
for(int val=0;val<[latArray count];val++){
NSString *dis_From_Current_Location;
dis_From_Current_Location =nil;

CGFloat str_Longitude=[[defaults objectForKey:@"long"]floatValue];
CGFloat str_Latitude=[[defaults objectForKey:@"lati"]floatValue]; 
   //Suppose this is your current location 

CGFloat lat1= [[latArray objectAtIndex:val]floatValue];
    //these array for lat
CGFloat long1=[[longArray objectAtIndex:val]floatValue];
    //these array for longArray
CLLocation *location1 = [[CLLocation alloc] initWithLatitude:lat1 longitude:long1];
CLLocation *location2 = [[CLLocation alloc] initWithLatitude:str_Latitude longitude:str_Longitude];
CLLocationDistance dist=[location1 distanceFromLocation:location2];
NSLog(@"Distance i meters: %f", [location1 distanceFromLocation:location2]);
long long v = llabs(dist/1000);
dis_From_Current_Location=[NSString stringWithFormat:@"%lld km",v];
[location1 release];
[location2 release];
[distanceArray addObject: dis_From_Current_Location];
//distanceArray is Global NsMutableArray.

}
}
-(void)getSoretdArray{
NSString * tempStr,*tempStr2;
for(int i=0;i<[distanceArray count]; i++){
    for(int j=i+1;j<[distanceArray count]; j++){
        if([distanceArray objectAtIndex:j]>[distanceArray objectAtIndex:j+1]){
            tempStr=[distanceArray objectAtIndex:j];
            NSString* str= [distanceArray objectAtIndex:j+1];
            [ distanceArray insertObject:str atIndex:j];
            [distanceArray insertObject:tempStr atIndex:j+1] ;
            //also change the name of corresponding location.
            //you have to adjust the stored names in namArray for storing names of Corresponding Distances 
            tempStr2=[nameArray objectAtIndex:j];
            NSString* str1= [nameArray objectAtIndex:j+1];
            [ nameArray insertObject:str1 atIndex:j];
            [nameArray insertObject:tempStr2 atIndex:j+1] ;


        }
    }
}
This will definitely work just try to use carefully
NSArray *orderedUsers = [users sortedArrayUsingComparator:^(id a,id b) {
     User *userA = (User *)a;
     User *userB = (User *)b;
     CLLocationDistance distanceA = [userA.location getDistanceFromLocation:myLocation];
     CLLocationDistance distanceB = [userB.location getDistanceFromLocation:myLocation];
     if (distanceA < distanceB) {
         return NSOrderedAscending
     } else if (distanceA > distanceB) {
         return NSOrderedDescending;
     } else {
         return NSOrderedSame;
     }
}];
- (void)viewDidLoad {
    [super viewDidLoad];
// This Array Taken Globally
List_of_locationsArray =[[NSMutableArray alloc]initWithObjects:
  @{@"latitude" : @"17.415045",@"logitude":@"78.421424"} ,@{@"latitude" : @"17.415045",@"logitude":@"78.421424"},@{@"latitude" : @"17.415045",@"logitude":@"78.421424"},@{@"latitude" : @"17.415045",@"logitude":@"78.421424"},@{@"latitude" : @"17.415045",@"logitude":@"78.421424"}
 ,nil];

}

-(void)sortingLocationsArray{
//    CLLocation* currentLocation =[[CLLocation alloc]initWithLatitude:[currentLatitude doubleValue] longitude:[currentLogitude doubleValue]];
      CLLocation* currentLocation =[[CLLocation alloc]initWithLatitude: currentLatitudeHere longitude:CurrentLogHere];

   NSMutableArray* tempLocationsArr = [[NSMutableArray alloc]initWithCapacity:[locationsArray count]];
    for (int i=0; i<[locationsArray count]; i++) {
        CLLocationDegrees latValue = [[locationsArray[i] objectForKey:@"latitude"] doubleValue];
        CLLocationDegrees longValue = [[locationsArray[i] objectForKey:@"logitude"] doubleValue];
        CLLocation* location = [[CLLocation alloc]initWithLatitude:latValue longitude:longValue];
        [tempLocationsArr addObject:location];

        NSArray* sortLocationArry = [tempLocationsArr sortedArrayUsingComparator:^NSComparisonResult(CLLocation* location1, CLLocation* location2) {
            CLLocationDistance distA = [location1 distanceFromLocation:currentLocation];
            CLLocationDistance distB = [location2 distanceFromLocation:currentLocation];
            if (distA < distB) {
                return NSOrderedAscending;
            } else if ( distA > distB) {
                return NSOrderedDescending;
            } else {
                return NSOrderedSame;
            }
        }];

      //ArrayAfterSorting is another mutable Array to Store Sorting Data
        [ArrayAfterSorting removeAllObjects];
        [sortLocationArry enumerateObjectsUsingBlock:^(CLLocation* location, NSUInteger idx, BOOL *stop) {
            NSMutableDictionary *tempDict = [[NSMutableDictionary alloc]init];
            [tempDict setObject:[NSString stringWithFormat:@"%f",location.coordinate.latitude] forKey:@"latitude"];
            [tempDict setObject:[NSString stringWithFormat:@"%f",location.coordinate.longitude] forKey:@"logitude"];
            [ArrayAfterSorting addObject:tempDict];


        }];
     NSLog(@"sortedArray : %@", ArrayAfterSorting);
    }

}