为解析查询计算 NSPredicate 中两个 PFGeopoints 之间的距离

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

我有一个特例,当我想做类似

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

基本上,我想get all photos that are taken within 10km around my current location if my current location is also within the photo's visible radius

此外,photoLocationvisibleRadius 是数据库中的两列,我将提供 UserLocation 作为 PFGeoPoint。

有可能实现吗?在我看来,我不认为我可以调用,例如 photoLocation.latitude 来获取特定的坐标值。我可以吗?

如果能实现,我将不胜感激!!

我在 pares.com 文档中找到了这个,这里是 link

let swOfSF = PFGeoPoint(latitude:37.708813, longitude:-122.526398)
let neOfSF = PFGeoPoint(latitude:37.822802, longitude:-122.373962)
var query = PFQuery(className:"PizzaPlaceObject")
query.whereKey("location", withinGeoBoxFromSouthwest:swOfSF, toNortheast:neOfSF)
var pizzaPlacesInSF = query.findObjects()

此代码为您获取由 swOfSF & neOfSF objectc 定义的矩形区域中的所有对象,其中 seOfSF 在西南角,neOfSF 在北角东角。

您可以对代码进行一些改动,并获取您的对象位于中间的矩形区域中的所有对象

我建议您不要使用半径,因为它会进行大量计算。而是使用矩形区域(就像我给你的代码)。

只需计算您所在位置的 max/min 经度和 max/min 纬度,然后获取介于两者之间的所有对象。您可以在此处阅读有关如何调整 min/max 经度和纬度的信息 Link

我设法使用 Parse Cloud Code 解决了它,这里是 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");
        }
    }); 
});

以上代码说明了如何使用 Cloud Code 的基本示例。除此之外,我必须确保所有返回的图像都在用户搜索范围和照片可见圈的联合中。还有更多的技巧比如Promises。但就我的目的而言,上面的代码应该就足够了。