2017-01-13 3 views
2

좌표사용자의 좌표 사이의 가장 가까운 위치를 찾아 내가 매개 변수로받는 함수 만들려면 배열

  1. 좌표 가득 배열
  2. 현재 사용자 위치

그리고 반환을 사용자의 위치와 배열 위치 사이의 가장 가까운 위치

let coord1 = CLLocation(latitude: 52.45678, longitude: 13.98765) 
let coord2 = CLLocation(latitude: 52.12345, longitude: 13.54321) 
let coord3 = CLLocation(latitude: 48.771896, longitude: 2.270748000000026) 

사용자 위치 기능 :

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
    var userLocation:CLLocation = locations[0] 
    let long = userLocation.coordinate.longitude; 
    let lat = userLocation.coordinate.latitude; 

    let coordinates = [ coord1, coord2, coord3] 

    userLocation = CLLocation(latitude: lat, longitude: long) 

    print("my location: \(userLocation)") 
    closestLocation(locations: coordinates, closestToLocation: userLocation) 
} 

좌표를 비교 함수

func closestLocation(locations: [CLLocation], closestToLocation location: CLLocation) -> CLLocation? { 

    if let closestLocation: CLLocation = locations.min(by: { userLocation.distance(from: $0) < userLocation.distance(from: $1) }) { 

     let distanceMeters = userLocation.distance(from: closestLocation) 
     let distanceKM = distanceMeters/1000 

     print("closest location: \(closestLocation), distance: \(distanceKM)") 
     return closestLocation 
    } else { 
     print("coordinates is empty") 
     return nil 
    } 

} 
다음

내 위치입니다3210

실제로 작동하지 않으며 내 closestLocation 함수는 항상 두 "가장 가까운 위치"사이의 거대한 거리를 반환합니다.

closest location: <+48.77189600,+2.27074800> +/- 0.00m (speed -1.00 mps/course -1.00) @ 14/01/2017 00:16:04 heure normale d’Europe centrale, distance: 5409.0 

당신이 볼 수 있듯이, 곳 (km)의 거리가 매우이다 : 나는 closestLocationdistanceKM를 인쇄 할 때

입력

closestLocation(locations: coordinates, closestToLocation: userLocation) 

편집

결과 매개 변수 이 위치가 동일한 도시 인 동안 거대합니다.

+0

당신이 location''인쇄 할 때 당신은 무엇을 어떻게해야합니까? 또한 각 iteration에서'distance'를 출력하여 그들이 어떤 값인지 확인하십시오. – TheAmateurProgrammer

+0

필요한 모든 질문을 수정했습니다. –

답변

4

당신은 정렬 기준 (귀하의 경우 거리)에 따라 최소의 요소를 찾을 수 Array.min(by:)를 사용할 수 있습니다

func closestLocation(locations: [CLLocation], closestToLocation location: CLLocation) -> CLLocation? { 
    if let closestLocation = locations.min(by: { location.distance(from: $0) < location.distance(from: $1) }) { 
     print("closest location: \(closestLocation), distance: \(location.distance(from: closestLocation))") 
     return closestLocation 
    } else { 
     print("coordinates is empty") 
     return nil 
    } 
} 

// We know the answer is coord3 and the distance is 0  
closestLocation(locations: [coord1, coord2, coord3], closestToLocation: coord3) 
+0

답장을 보내 주셔서 감사합니다. 그러나 기능이 8968450 미터의 거리를 반환하는 이유는 무엇입니까? –

+0

그건 말이되지 않습니다. 입력 패러미터가'nearestLocation' 함수에 전달 될 수 있습니까? –

+0

필요한 모든 질문을 수정했습니다. –

관련 문제