【问题标题】:Find closest longitude and latitude in array from user location从用户位置查找数组中最近的经度和纬度
【发布时间】:2014-07-16 14:29:13
【问题描述】:

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

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

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];

【问题讨论】:

    标签: ios objective-c mkmapview cllocationmanager cllocationdistance


    【解决方案1】:

    您只需要遍历数组检查距离。

    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;
        }
    }
    

    在循环结束时,您将获得最小的距离和最近的位置。

    【讨论】:

    • DOUBLE_MAX 变量是做什么用的?
    • DOUBLE_MAX 将smallestDistance 变量设置为可能的最大数字。您可以将其设置为任何值,但如果您最初将其设置为 100,那么如果与数组的最小距离实际上是 150,那么您将遇到问题。
    • @Fogmeister 你不应该更新“smallestDistance”而不是“distance”吗?
    【解决方案2】:

    @Fogmeister

    我认为这是一个必须纠正 DBL_MAX 和分配的错误。

    首先:使用 DBL_MAX 而不是 DOUBLE_MAX。

    DBL_MAX 是 math.h 中的 #define 变量。
    它是最大可表示的有限浮点(双)数的值。

    第二:在你的情况下,你的分配是错误的:

    if (distance < smallestDistance) {
            distance = smallestDistance;
            closestLocation = location;
    }
    

    你必须这样做:

    if (distance < smallestDistance) {
            smallestDistance = distance;
            closestLocation = location;
    }
    

    不同之处在于将距离值分配给 minimumDistance,而不是相反。

    最终结果:

    NSArray *locations = //your array of CLLocation objects
    CLLocation *currentLocation = //current device Location
    
    CLLocation *closestLocation;
    CLLocationDistance smallestDistance = DBL_MAX; // set the max value
    
    for (CLLocation *location in locations) {
        CLLocationDistance distance = [currentLocation distanceFromLocation:location];
    
        if (distance < smallestDistance) {
            smallestDistance = distance;
            closestLocation = location;
        }
    }
    NSLog(@"smallestDistance = %f", smallestDistance);
    

    你能确认这是正确的吗?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-14
      • 1970-01-01
      • 2016-10-16
      • 2019-01-20
      相关资源
      最近更新 更多