가장 가까운 위치를 얻기 위해 다음 코드가 있습니다.
내 데이터 :
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)
closestLocation(locations: [coord1, coord2, coord3], closestToLocation: coord3)
// This calculates closest location giving out 1 point
func closestLocation(locations: [CLLocation], closestToLocation location: CLLocation) -> CLLocation? {
if let closestLocation = locations.min(by: { location.distance(from: $0) < location.distance(from: $1) }) {
print("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
print("Closest location: \(closestLocation), \n distance: \(location.distance(from: closestLocation))")
return closestLocation
} else {
print("coordinates is empty")
return nil
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
var userLocation:CLLocation = locations[0]
let long = userLocation.coordinate.longitude;
let lat = userLocation.coordinate.latitude;
userLocation = CLLocation(latitude: lat, longitude: long)
print("My location: \(userLocation)")
}
비교하기 위해 4 번째 배열에 가장 가까운 2 개를 계산하려면 어떻게해야합니까?
내 생각은 사용자의 현재 위치를 가져 와서 DB에 저장 한 다음 일부 게시물을 위치별로 정렬하는 것입니다. 그렇다면 사용자 위치와 게시물 위치가 있으면 사용자와 가장 가까운 2를 어떻게 찾을 수 있습니까?
감사
최소값을 찾는 데 사용한 것과 동일한 클로저를 기준으로 배열을 정렬하는 sorted(by:)
대신 호출 min(by:)
만하면됩니다. 그런 다음 첫 번째 n
요소 n
를 사용하여 사용자에게 가장 가까운 좌표를 얻을 수 있습니다 .
extension Array where Element == CLLocation {
func sortedByDistance(to location: CLLocation) -> [CLLocation] {
return sorted(by: { location.distance(from: $0) < location.distance(from: $1) })
}
}
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)
let coords = [coord1, coord2, coord3]
let sortedCoordinates = coords.sortedByDistance(to: coord3)
print(sortedCoordinates)
let closestTwoCoordinates = sortedCoordinates.prefix(2)
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다