2

経度と緯度でいっぱいの配列があります。ユーザーの場所に2つの二重変数があります。ユーザーの位置間の距離を配列に対してテストして、どの位置が最も近いかを確認したいと思います。どうすればいいですか?

これは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];
4

2 に答える 2

3

距離をチェックして配列を反復処理するだけです。

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

ループの終わりには、最短距離と最も近い場所が表示されます。

于 2014-07-16T14:51:22.760 に答える
2

@フォグマイスター

これは、DBL_MAX と代入について正しく設定する必要がある間違いだと思います。

最初: DOUBLE_MAX の代わりに DBL_MAX を使用します。

DBL_MAXは math.h の #define 変数です。
これは、表現可能な有限浮動小数点 (倍精度) 数の最大値です。

2番目:あなたの状態では、割り当てが間違っています:

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

あなたがしなければならない:

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

違いは、距離値が最小距離に割り当てられることであり、その逆ではありません。

最終結果:

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

それが正しいことを確認できますか?

于 2015-04-24T11:35:58.150 に答える