iPhone:根据位置排序

时间:2012-02-16 08:45:16

标签: iphone ios sorting

我一直在开发一款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";
    }
)

我需要通过计算纬度和经度,根据我所在位置附近的位置对用户进行排序。到目前为止我无法做到这一点。有人可以帮我提供一些样品吗?

更新:根据Mr.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;
    }
}];

谢谢!

5 个答案:

答案 0 :(得分:9)

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;
     }
}];

答案 1 :(得分:3)

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

在数学上说,这是一个Wolfram|Alpha example

现在“programmatic-ally”,你可以使用CLLocation类,这是一个例子:

(CLLocationDistance)getDistanceFrom:(const CLLocation *)location

但首先您需要从纬度和经度创建位置对象。您可以使用:

(id)initWithLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude

答案 2 :(得分:1)

您可以计算您的头寸与每个商品的头寸和订单之间的distance (geographical, not flat plane!)

答案 3 :(得分:0)

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.

}
}

现在您应该应用排序方法(选择,气泡)来排序距离。

需要注意的一件事是当你对distanceArray进行排序时 请根据distanceArray调整nameArray的值 请参阅下面的代码,用于对distanceArray进行排序并调整nameArray的值。

-(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

答案 4 :(得分:0)

- (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);
    }

}