Reputation: 3444
I am having issues writing a Parse query to get a Parse object with a GeoPoint that is CLOSEST to the inputted GeoPoint. Currently, the code appears to be returning the most recently created object.
Code:
// check Parse for infections around passed GeoPoint
Parse.Cloud.define("InfectionCheck_BETA", function(request, response) {
var returnCount;
var geoPoint = request.params.geoPoint;
var query = new Parse.Query("InfectedArea");
query.withinMiles("centerPoint", geoPoint, 1); // check for infections within one mile
Parse.Promise.as().then(function() {
// query for count of infection in area, this is how we get severity
return query.count().then(null, function(error) {
console.log('Error getting InfectedArea. Error: ' + error);
return Parse.Promise.error(error);
});
}).then(function(count) {
if (count <= 0) {
// no infected areas, return 0
response.success(0);
}
returnCount = count;
return query.first().then(null, function(error) {
console.log('Error getting InfectedArea. Error: ' + error);
return Parse.Promise.error(error);
});
}).then(function(result) {
// we have the InfectedArea in question, return an array with both
response.success([returnCount, result]);
}, function(error) {
response.error(error);
});
});
What I want is for the first() query to return the object with the CLOSEST GeoPoint in the centerPoint
key.
I have tried adding query.near("centerPoint", geoPoint)
and query.limit(1)
to no avail as well.
I have seen iOS PFQueries calling whereKey:nearGeoPoint:withinMiles:
that supposably returns sorted based on nearest GeoPoints. Is there a JavaScript equivalent that works like this?
Upvotes: 4
Views: 2901
Reputation: 5960
Would you try this? If all the distances are the same, then Parse isn't sorting to the precision that you need.
// check Parse for infections around passed GeoPoint
Parse.Cloud.define("InfectionCheck_BETA", function(request, response) {
var geoPoint = request.params.geoPoint;
var query = new Parse.Query("InfectedArea");
query.near("centerPoint", geoPoint);
query.limit(10);
query.find({
success: function(results) {
var distances = [];
for (var i = 0; i < results.length; ++i){
distances.push(results[i].kilometersTo(geoPoint));
}
response.success(distances);
},
error: function(error) {
response.error("Error");
}
});
});
This results in the ten closest distances.
After chatting, it seems that the reason that the distances weren't being sorted is that Parse only sorts with accuracy of a few centimeters. The differences the user was looking at were less than that.
Upvotes: 6