我正在开展一个项目,其中我必须显示用户位置的多个位置的距离。地点以纬度和经度为基础。
我使用以下代码来获得两个位置之间的距离显示几乎相同的距离
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作为用户的位置
答案 0 :(得分:2)
您可以使用以下方法查找距离
#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"和#34; longArray"你可以通过循环迭代。距离是用户的位置和阵列中的位置之间的距离。获得的距离以公里为单位。
答案 1 :(得分:1)
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
答案 2 :(得分:1)
Swift版本:
let currentLocation: CLLocation = //current location
let otherLocations: [CLLocation] = //the locations you want to know their distance to currentLocation
let distances = otherLocations.map { $0.distanceFromLocation(currentLocation) }