1

나는 경도와 위도가 모두있는 배열을 가지고 있습니다. 내 사용자 위치에 두 개의 이중 변수가 있습니다. 내 배열과 내 사용자의 위치 간 거리를 테스트하여 가장 가까운 위치를 확인하고 싶습니다. 어떻게해야합니까?사용자 위치에서 가장 가까운 경도와 위도를 배열로 찾으십시오.

이것은 두 위치 사이의 거리를 가져 오지만 위치 배열에 대해 테스트하는 방법을 이해하기에 튼튼합니다.

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

답변

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

루프의 끝에서 가장 가까운 거리와 가장 가까운 위치에 있습니다.

+0

DOUBLE_MAX var은 무엇을 위해 사용됩니까? – user3626407

+0

DOUBLE_MAX는 'smallestDistance' 변수를 가능한 가장 큰 수로 설정합니다. 아무것도 설정할 수 없지만 처음에 '100'으로 설정하면 배열에서 최소 거리가 실제로 '150'이면 문제가 발생합니다. – Fogmeister

+0

@ Fogmeister "거리"대신 "smallestDistance"를 업데이트하지 않아야합니까? –

2

@Fogmeister 나는이 잘 DBL_MAX과 과제에 대해 설정해야 실수라고 생각합니다.

첫 번째 : DOUBLE_MAX 대신 DBL_MAX를 사용하십시오.

DBL_MAX는 math.h의 #define 변수입니다.
최대 표현 가능한 유한 부동 소수점 (double) 수의 값입니다. 둘째

: 당신의 상태에서, 당신의 임무는 잘못된 것입니다 :

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

당신은 수행해야합니다

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

차이가 지정한 거리 smallestDistance에 값이 아닌 것입니다 반대말.

최종 결과

는 :

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

당신은이 정확한지 확인할 수 있습니까?

+1

이유는 "편집"버튼이 있습니다. – Fogmeister