ios - 在数组中查找距用户位置最近的经度和纬度

标签 ios objective-c mkmapview cllocationmanager cllocationdistance

我有一个充满经度和纬度的数组。我的用户位置有两个双变量。我想根据我的阵列测试用户位置之间的距离,看看哪个位置最近。我该怎么做?

这将获得两个位置之间的距离,但很难理解 我如何针对一系列位置对其进行测试。

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/

相关文章:

ios - Apple Watch 设置背景图片

ios - 加载 View Controller 后的画外音顺序

ios - MKAnnotation 点击​​时没有响应

ios - 如何快速将正确的标注附件添加到自定义注释?

ios - .o 文件中缺少汇编函数

ios - 没有找到合适的申请记录。验证您的包标识符 'com.swiftyjson.SwiftyJSON' 是否正确

ios - Auto Layout 可以用来代替 Asset Catalog 吗?

IOS/objective-C/ swift /语音 : Specify Locale when declaring SFSpeech Recognizer variable

IOS 在使用 Compact Regular 和 Compact Any Size 类时的区别

ios - 如何使用 Apple MapKit 从 VisibleRegion 获取纬度/经度坐标?