gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:19:16 24 4
gpt4 key购买 nike

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

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

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

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

最佳答案

首先,不要为纬度和经度创建两个数组,它应该是一个 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 - 如何从一个位置获取数组中多个位置的距离并在 iOS 中按最近距离对该数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40394685/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com