【问题标题】:How to get the distance of multiple location in array from one location and Sort that array by nearest distance in iOS?如何从一个位置获取数组中多个位置的距离并在iOS中按最近距离对该数组进行排序?
【发布时间】:2017-03-16 15:15:01
【问题描述】:

我正在做一个项目,我必须显示多个位置与一个位置的距离。位置基于纬度和经度。

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

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作为一个位置..

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

【问题讨论】:

    标签: ios


    【解决方案1】:

    首先,不要为经纬度创建两个数组,它应该是一个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);
    
        }];
    

    【讨论】:

    • 感谢回答@iOS_developer
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多