2015-11-25 24 views
5

在發佈here的問題,用戶問:從用戶位置查找最接近陣列經度和緯度 - iOS設備斯威夫特

我有一個數組全經度和緯度的。我有兩個雙重變量與我的用戶位置。我想測試我的用戶位置與陣列之間的距離,以查看哪個位置最接近。我該怎麼做呢?

這將得到2個位置之間的距離,但拼圖理解我將如何對陣位置進行測試。

對此,他得到了下面的代碼:

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

我有一個應用程序完全相同的問題我的工作,我覺得這一段代碼可以很好地工作。但是,我正在使用Swift,並且此代碼位於Objective-C中。

我唯一的問題是:它應該如何看待Swift?

感謝您的任何幫助。我對這一切都很陌生,看到Swift中的這段代碼可能會是一個大問題。

回答

16
var closestLocation: CLLocation? 
var smallestDistance: CLLocationDistance? 

for location in locations { 
    let distance = currentLocation.distanceFromLocation(location) 
    if smallestDistance == nil || distance < smallestDistance { 
    closestLocation = location 
    smallestDistance = distance 
    } 
} 

print("smallestDistance = \(smallestDistance)") 

或作爲一個函數:

func locationInLocations(locations: [CLLocation], closestToLocation location: CLLocation) -> CLLocation? { 
    if locations.count == 0 { 
    return nil 
    } 

    var closestLocation: CLLocation? 
    var smallestDistance: CLLocationDistance? 

    for location in locations { 
    let distance = location.distanceFromLocation(location) 
    if smallestDistance == nil || distance < smallestDistance { 
     closestLocation = location 
     smallestDistance = distance 
    } 
    } 

    print("closestLocation: \(closestLocation), distance: \(smallestDistance)") 
    return closestLocation 
} 
+0

現在我可以使用此與比較Objective-C的。這種方式比一種更有幫助。謝謝! – tsteve

+0

很高興我能幫忙! –

14

對於夫特3我已經創建這個小片的 「功能性」 的代碼:

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

let coordinates = [coord1, coord2, coord3] 

let userLocation = CLLocation(latitude: 52.23678, longitude: 13.55555) 

let closest = coordinates.min(by: 
{ $0.distance(from: userLocation) < $1.distance(from: userLocation) }) 
相關問題