Hello! I am wondering if it is possible to sort table entries by distance from a point! I know that the distanceBySphere function is able to be added to a where clause to find all the points within a certain radius of another point. Is there a way to get a sorted list by proximity of those results?
@Dustin_Pierce sure, here it is swift example:
I have column p
it is a Point, we add distanceOnSphere( p, 'POINT(5 5)') as d
and p
as property,
also we find with where d > 1
and sort by d DESC
let queryBuilder = DataQueryBuilder()
queryBuilder.setWhereClause(whereClause: "d > 1")
queryBuilder.setProperties(properties: ["distanceOnSphere( p, 'POINT(5 5)') as d", "p"])
queryBuilder.setSortBy(sortBy: ["d DESC"])
Backendless.shared.data.ofTable("test").find(queryBuilder: queryBuilder
, responseHandler: { foundObjects in
print("Found objects: \(foundObjects)")
}, errorHandler: { fault in
print("Error: \(fault.message ?? "")")
})
}
and result is:
Found objects: [
["d": 785765.4941524031, "objectId": "228D891D-6EF4-D589-FF6D-563E56E0F400", "p": <Backendless.BLPoint: 0x6000029c8460>, "___class": "test"],
["p": <Backendless.BLPoint: 0x6000029c84b0>, "d": 628516.7873194569, "___class": "test", "objectId": "420E1CDA-3AE6-ECAE-FF1F-A91D5991B600"],
["d": 471292.0511888224, "p": <Backendless.BLPoint: 0x6000029c86e0>, "objectId": "4626DD7D-7E5E-C246-FF7A-F2BC662F8E00", "___class": "test"]]
and almost the same but we sort d ASC
let queryBuilder = DataQueryBuilder()
queryBuilder.setWhereClause(whereClause: "d > 1")
queryBuilder.setProperties(properties: ["distanceOnSphere( p, 'POINT(5 5)') as d", "p"])
queryBuilder.setSortBy(sortBy: ["d ASC"])
Backendless.shared.data.ofTable("test").find(queryBuilder: queryBuilder
, responseHandler: { foundObjects in
print("Found objects: \(foundObjects)")
}, errorHandler: { fault in
print("Error: \(fault.message ?? "")")
})
and result:
Found objects: [
["p": <Backendless.BLPoint: 0x600001ad5400>, "objectId": "4626DD7D-7E5E-C246-FF7A-F2BC662F8E00", "d": 471292.0511888224, "___class": "test"],
["___class": "test", "p": <Backendless.BLPoint: 0x600001ad5450>, "d": 628516.7873194569, "objectId": "420E1CDA-3AE6-ECAE-FF1F-A91D5991B600"],
["___class": "test", "objectId": "228D891D-6EF4-D589-FF6D-563E56E0F400", "p": <Backendless.BLPoint: 0x600001ad4c30>, "d": 785765.4941524031]]