Я ищу сортировку по ближайшим точкам к моему текущему местоположению — массив CLLocationCoordinate2D в Swift

#ios #swift #xcode #swift5

#iOS #swift #xcode #swift5

Вопрос:

Я ищу сортировку по ближайшим точкам к моему текущему местоположению — массив CLLocationCoordinate2D в Swift

Вот мой код

     let json =  try JSON(data: getJSON(urlToRequest: API_URL_POSITIONS) as Data)
  
            let results: [JSON] = json.array ?? []
         
            let array: [CLLocationCoordinate2D] = results
                .map({ $0["vehicle"]["position"] })
                .compactMap({ (json) -> CLLocationCoordinate2D? in
                    guard let longitude = json["longitude"].double else { return nil }
                    guard let latitude = json["latitude"].double else { return nil }
                    return CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
                })
        
        let   camera  = GMSCameraPosition.camera(withLatitude: (self.locationManager.location?.coordinate.latitude)!  , longitude: (self.locationManager.location?.coordinate.longitude)!, zoom: 10)

        if (mapView == nil)  {
          mapView = GMSMapView.map(withFrame: self.view.bounds, camera: camera)
          self.view.addSubview(mapView!)
        }
         
          mapView?.settings.myLocationButton = true
          mapView?.isMyLocationEnabled = true
        mapView?.mapType =  .terrain
        var counter = 0
        let pin = UIImage(named: "bus")!
                                  

        
       for location in array{
           print("location: (location)")
           let marker = GMSMarker()
        marker.icon = pin
           marker.position = location
           marker.tracksInfoWindowChanges = true
        marker.snippet = results[counter]["vehicle"]["vehicle"]["label"].stringValue
           marker.map = mapView
       counter = counter   1
        
       }
        
    }
    catch {
        print ("error")
    }
 

Мне нужно вернуть только ближайшие 5 местоположений в этом коде.

Комментарии:

1. locations.sort { ... }.prefix(5)

Ответ №1:

Используйте этот метод для сортировки координат, ближайших к текущим координатам.

 func getNearestPoints(array: [CLLocationCoordinate2D], currentLocation: CLLocationCoordinate2D) -> [CLLocationCoordinate2D]{
    let current = CLLocation(latitude: currentLocation.latitude, longitude: currentLocation.longitude)
    var dictArray = [[String: Any]]()
    for i in 0..<array.count{
        let loc = CLLocation(latitude: array[i].latitude, longitude: array[i].longitude)
        let distanceInMeters = current.distance(from: loc)
        let a:[String: Any] = ["distance": distanceInMeters, "coordinate": array[i]]
        dictArray.append(a)
    }
    
    dictArray = dictArray.sorted(by: {($0["distance"] as! CLLocationDistance) < ($1["distance"] as! CLLocationDistance)})
    var sortedArray = [CLLocationCoordinate2D]()
    for i in dictArray{
        sortedArray.append(i["coordinate"] as! CLLocationCoordinate2D)
    }
    return sortedArray
}