Search code examples
objective-cswiftparse-platformpfquery

Calculate distance between two PFGeopoints in a NSPredicate for a Parse Query


I have a special case when I want to do something like

let predicate = NSPredicate(format:"
    DISTANCE(\(UserLocation),photoLocation) <= visibleRadius AND
    DISTANCE(\(UserLocation),photoLocation" <= 10)"
var query = PFQuery(className:"Photo", predicate:predicate)

Basically, I want to get all photos that are taken within 10km around my current location if my current location is also within the photo's visible radius

Also, photoLocation and visibleRadius are two columns in the database, I will supply UserLocation as a PFGeoPoint.

Is it possible to achieve this? In my opinion, I don't think that I may call, for example, photoLocation.latitude to get a specific coordinate value. May I?

I'll appreciate you a lot if this can be achieved!!


Solution

  • I managed to solve it using Parse Cloud Code, here is the quick tutorial

    Parse.Cloud.define("latestPosts", function(request, response) {
        var limit = 20;
        var query = new Parse.Query("Post");
        var userLocation = request.params.userLocation;
        var searchScope = request.params.searchScope;
        var afterDate = request.params.afterDate;
        var senderUserName = request.params.senderUserName;
        query.withinKilometers("Location", userLocation, searchScope);
        query.greaterThan("createdAt", afterDate);
        query.notEqualTo("senderUserName",senderUserName);
        query.ascending("createdAt");
        query.find({
            success: function(results) {
                var finalResults = results.filter(function(el) {
                    var visibleRadius = el.get("VisibleRadius");
                    var postLocation = el.get("Location");
                    return postLocation.kilometersTo(userLocation) <= visibleRadius;
                });
                if (finalResults.length > limit) {
                    var slicedFinalResults = results.slice(0, 20);
                    response.success(slicedFinalResults);
                } else {
                    response.success(finalResults);
                }
            },
            error: function() {
                response.error("no new post");
            }
        }); 
    });
    

    The code above illustrate a basic example of how to use Cloud Code. Except, I have to make sure that all the returned image are in the union of user's search scope and photo's visible circle. There are more techniques such as Promises. But for my purpose, the code above should just suffice.