如何从一个位置获取阵列中多个位置的距离并在iOS中按最近距离对该阵列进行排序?

时间:2016-11-03 05:52:08

标签: ios

我正在开展一个项目,我必须从一个位置显示多个位置的距离。地点以纬度和经度为基础。

我使用以下代码来获取两个位置之间的距离显示几乎相同的距离

CLLocation *locationA = [[CLLocation alloc] initWithLatitude:28.6379 longitude: 77.2432];CLLocation *locationB = [[CLLocation alloc] initWithLatitude:28.6562 longitude:77.2410];CLLocationDistance distance = [locationA distanceFromLocation:locationB];NSLog(@"Distance is %f",distance);float i  = distance/1000;NSLog(@"distance between two places is %f KM", i);

但现在我是结构,以便从我的位置获取多个位置的距离:locationA。

例如,我将NSArray作为纬度和经度

NSArray * latitudeArray = [[NSArray alloc]initWithObjects:@"28.6129",@"28.6020",@"28.5244", nil];NSArray * longitudeArray = [[NSArray alloc]initWithObjects:@"77.2295",@"77.2478",@"77.1855", nil];

请帮我解决..

将locationA作为一个位置..

请帮我按最近的距离对数组进行排序..

1 个答案:

答案 0 :(得分:2)

首先,不要为纬度和经度创建两个数组,它应该是一个CLLocations数组。

  NSMutableArray locationsArray = [[NSMutableArray alloc] init];
    //This is just for example, You should add locations to this array according to format of data you have available.

    [locationsArray addObject:[[CLLocation alloc] initWithLatitude:28.6379 longitude:77.2432]];
    [locationsArray addObject:[[CLLocation alloc] initWithLatitude:28.6020 longitude:77.2478]];
    [locationsArray addObject:[[CLLocation alloc] initWithLatitude:28.5244 longitude:77.1855]];

现在,拿一些参考位置,

CLLocation *yourLocationA ; //set whatever value you have..

您可以按照以下方式对位置数组进行排序。

 [locationsArray sortUsingComparator:^NSComparisonResult(CLLocation *obj1Location,CLLocation *obj2Location) {
            CLLocationDistance obj1Distance = [obj1Location distanceFromLocation: yourLocationA];
            CLLocationDistance obj2Distance = [obj2Location distanceFromLocation: yourLocationA];

            return (obj1Distance > obj2Distance);

    }];