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

前端 未结 3 1101
长发绾君心
长发绾君心 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:51

    For Swift 3 I have created this little piece of "functional" code:

    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) })
    
    0 讨论(0)
  • 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)")
    }
    
    0 讨论(0)
  • 2021-02-08 12:56
    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)")
    

    or as a function:

    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 讨论(0)
提交回复
热议问题