0

I have the response of an API in JSON format. How can I sort the results from least to greatest distance in a tableView (UIKit) with respect to the user's location? and calculate the distance between both points.

This is one of the answers:

 {
 "PlaceId": "ChIJjS5n_YLMj4ARlfgRtxtoW00",
 "PlaceName": "IHOP",
 "Address": "644 N 1st St, San Jose",
 "Category": "restaurant",
 "IsOpenNow": "Open now",
 "Latitude": 37.348115,
 "Longitude": -121.8990835,
 "Thumbnail": "https://maps.googleapis.com/maps/api/place/photo?maxwidth=2400&photoreference=CmRaAAAAe8OYJqvYpTKJR3EkuxBukX1ox0gm9-8NNO19OvbCRtiSvKHthC_3_8KAsq6-ARBRR1T-zzigB8k8THFVAQsYTJD3ibe_LE_Cwi4whBVkKBhO6R-HQIpKpFYVcDAq3rEoEhANPd06Rb2KwWN3HGJ0rVBhGhRLWqZY9nHwHf7tCRSMjiYtmeD1Lw&key=AIzaSyBKYncKJA-Uu060807q_t3g1Y6o6Y9fyaI",
 "Rating": 4.2,
 "IsPetFriendly": false,
 "AddressLine1": "644 N 1st St",
 "AddressLine2": "San Jose",
 "PhoneNumber": "(664) 326 2312",
 "Site": "http://www.arkusnexus.com"
 }

The response is stored in an array.

screenshot of the request

  • 2
    https://stackoverflow.com/questions/35199363/sort-array-by-calculated-distance-in-swift ? – Larme May 26 '22 at 19:55

1 Answers1

0

You can use sortPlace function to sort the results from least to greatest distance with respect to the user's location

    func sortPlaces(places: [DataModel]) -> [DataModel]  {
    let userLocation = CLLocation(latitude: userLat, longitude: userLong)
    
    let sortedPlaces = places.sorted { place1, place2 in
        let place1Location = CLLocation(latitude: CLLocationDegrees(place1.Latitude), longitude: place1.Longitude)
        let place1Distance = userLocation.distance(from: place1Location)
        
        let place2Location = CLLocation(latitude: CLLocationDegrees(place2.Latitude), longitude: place2.Longitude)
        let place2Distance = userLocation.distance(from: place2Location)
        
        return place1Distance < place2Distance
    }
    
    return sortedPlaces
}