iPhone: сортировка по местоположению - PullRequest
3 голосов
/ 16 февраля 2012

Я работал над приложением для 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";
    }
)

Мне нужно отсортировать пользователей по местоположению, которое находится рядом с моим местоположениемвычисляя широту и долготу.Я не могу достичь этого до сих пор.Может ли кто-нибудь помочь мне с предоставлением образцов?

ОБНОВЛЕНО: Я пытаюсь, как показано ниже, в соответствии с предложением господина.Пожалуйста, проверьте мой обновленный код.Это нормально?

    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 ]

9 голосов
/ 16 февраля 2012
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;
     }
}];
3 голосов
/ 16 февраля 2012

Во-первых, вам необходимо рассчитать расстояние между вашим текущим местоположением и местоположением другого пользователя.

Говоря математически, вот пример Wolfram | Alpha

Теперь "программно-союзник", вы можете использовать CLLocation класс, вот пример:

(CLLocationDistance)getDistanceFrom:(const CLLocation *)location

Но сначала вам нужно будет создать объект местоположения из вашей широты и долготы. Вы можете использовать:

(id)initWithLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude
1 голос
/ 16 февраля 2012

Вы можете рассчитать расстояние (географическое, а не плоскую плоскость!) между вашей позицией и позицией каждого из этих предметов и порядком по этому значению.

0 голосов
/ 08 ноября 2017
- (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);
    }

}
0 голосов
/ 16 февраля 2012
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 пожалуйста, отрегулируйте значения nameArray в соответствии с distanceArray См. Ниже код для сортировки 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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...