我有一个充满经度和纬度的数组。我的用户位置有两个双变量。我想根据我的阵列测试用户位置之间的距离,看看哪个位置最近。我该怎么做?
这将获得两个位置之间的距离,但很难理解 我如何针对一系列位置对其进行测试。
CLLocation *startLocation = [[CLLocation alloc] initWithLatitude:userlatitude longitude:userlongitude];
CLLocation *endLocation = [[CLLocation alloc] initWithLatitude:annotation.coordinate.latitude longitude:annotation.coordinate.longitude];
CLLocationDistance distance = [startLocation distanceFromLocation:endLocation];
最佳答案
您只需迭代数组检查距离即可。
NSArray *locations = //your array of CLLocation objects
CLLocation *currentLocation = //current device Location
CLLocation *closestLocation;
CLLocationDistance smallestDistance = DOUBLE_MAX;
for (CLLocation *location in locations) {
CLLocationDistance distance = [currentLocation distanceFromLocation:location];
if (distance < smallestDistance) {
smallestDistance = distance;
closestLocation = location;
}
}
在循环结束时,您将获得最小距离和最近位置。
关于ios - 在数组中查找距用户位置最近的经度和纬度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24783442/