iOS: 如何获取多个位置与一个位置的距离

iOS: How to get the distance of multiple location from one location

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

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

CLLocation *locA = [[CLLocation alloc] initWithLatitude:28.6379 longitude: 77.2432];
CLLocation *locB = [[CLLocation alloc] initWithLatitude:28.6562 longitude:77.2410];

CLLocationDistance distance = [locA distanceFromLocation:locB];
NSLog(@"Distance is %f",distance);
float i  = distance/1000;
NSLog(@"distance between two places is %f KM", i);

但现在我可以从我的位置获取多个位置的距离:locaA。

例如我将 NSarray 用于纬度和经度

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

请帮我解决一下

将locaA作为用户位置

您可以使用以下方法计算距离

#define DEG2RAD(degrees) (degrees * 0.01745327)  

 double currentLatitudeRad = DEG2RAD(currentLatitude);
 double currentLongitudeRad = DEG2RAD(currentLongitude);
 double destinationLatitudeRad = DEG2RAD(destinationLatitude);
 double destinationLongitudeRad = DEG2RAD(destinationLongitude);  

double distance  =  acos(sin(currentLatitudeRad) * sin(destinationLatitudeRad) + cos(currentLatitudeRad) * cos(destinationLatitudeRad) * cos(currentLongitudeRad - destinationLongitudeRad)) * 6880.1295896;  

这里,currentLatitude 和currentLongitude 是用户的位置。 destinationLatitude 和 destinationLongitude 是数组 "latArray" 和 "longArray" 中的每个对象,您可以通过 for 循环对其进行迭代。 distance 是用户位置与数组中位置之间的距离。获得的距离将以公里为单位。

CLLocation *currentLocation = ... // This is a reference to your current location as a CLLocation
NSArray *arrayOfOtherCLLocationObjects = ... // This is an array that contains all of the other points you want to calculate the distance to as CLLocations

NSMutableArray *distancesFromCurrentLocation = [[NSMutableArray alloc] initWithCapacity:arrayOfOtherCLLocationObjects.count]; // We will add all of the calculated distances to this array

for (CLLocation *location in arrayOfOtherCLLocationObjects) // Iterate through each location object
{
  CLLocationDistance distance = [location distanceFromLocation:currentLocation]; // Calculate distance
  [distancesFromCurrentLocation addObject:@(distance)]; // Append distance to array. You need to wrap the distance object as an NSNumber so you can append it to the array.
}

// At this point, you have the distance for each location point in the array distancesFromCurrentLocation

Swift版本:

let currentLocation: CLLocation = //current location
let otherLocations: [CLLocation] = //the locations you want to know their distance to currentLocation

let distances = otherLocations.map { [=10=].distanceFromLocation(currentLocation) }