Algolia sorting by geolocation in Swift

Hi,

I am working on a project that uses Algolia for searching and sorting.

I have a problem with Algolia geolocation sorting in iOS App.
I need to display all documents in a range of 100 km from the user location.
I have multiple documents in my Indice. The document looks like this:

"document": {
    "price": 5000,
    "unit": "cały projekt",
    "_geoloc": {
      "lat": 54.5,
      "lng": 18.55
    },
    "title": "Test ogloszenia",
    "range": 0,
    "activeFrom": {
      "_seconds": 1597042800,
      "_nanoseconds": 0
    }
}

In my Algolia Ranking and Sorting, I have default set GEO.

My Swift code for sorting locations looks like below:

func getAnnouncesLocation(location: CLLocationCoordinate2D, completion: @escaping ([Announcement]) -> ()) {
        var announcementsArray = [Announcement]()
        let query = Query(query: "")
        
        
        query.aroundLatLng = LatLng(lat: location.latitude, lng: location.longitude)
        query.aroundRadius = .explicit(100000) // 100 km
        collectionIndex = searchClient.index(withName: "products_geolocation")
        collectionIndex.search(query) { (content, error) in
            guard let content = content else {
                if let error = error {
                    print(error.localizedDescription)
                    
                }
                  
                return
            }
            print("HITS \(content)")
        }
     }

The code doesn’t return any error but the content is empty.
Another sorting like by price works perfectly. The only problem is with geolocation.
If that can help to set sorting by the price I need to add a sort-by attribute like this: document.price in Dashboard.

I am saving data to Algolia from my server in Node.js and there I am creating _geoloc value.
The latitude and longitude are hardcoded for testing so there isn’t a problem with async.

Thank you for any kind of help.

Regards
Matt

Hi @matt11,

The code snippet you provided looks good to me.
Did you try to apply geo sorting using Algolia Dashboard?

Hi, I found a bug in my project.
While sending the document to Algolia I send like this:

   const record = {
        objectID: doc.id,
        document: document
    };

where document contained all properties and also _geoloc property. After some investigation, I separated _geoloc from the document I sent it like below:

   const record = {
        objectID: doc.id,
        document: document,
        _geoloc: coordinates

    };

Now everything works fine.

Cheers :tada:

That’s perfect :slight_smile:

By the way, I see you use the version 7 of the Swift API Client.
Is there any particular reason you don’t consider to try the v8? It includes the last Algolia features and bug fixes.