Find closest longitude and latitude in array from user location - iOS Swift

前端 未结 3 1104
长发绾君心
长发绾君心 2021-02-08 12:16

In the question posted here, the user asked:

I have an array full of longitudes and latitudes. I have two double variables with my users location. I\'d like

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-08 12:53

        func closestLoc(userLocation:CLLocation){
        var distances = [CLLocationDistance]()
        for location in locations{
            let coord = CLLocation(latitude: location.latitude!, longitude: location.longitude!)
            distances.append(coord.distance(from: userLocation))
            print("distance = \(coord.distance(from: userLocation))")
        }
    
        let closest = distances.min()//shortest distance
        let position = distances.index(of: closest!)//index of shortest distance
        print("closest = \(closest!), index = \(position)")
    }
    

提交回复
热议问题