流星:用两点

时间:2015-08-07 10:28:28

标签: javascript mongodb meteor geojson

我正在构建一个汽车共享应用程序并设置游乐设施,我在我的数据库中有这种插入:

    {
        "_id": "YyPpkCDhTKStGw6CL",
        "authorId": "W6zvbcqit4Mw6a2iK",
        "stages": [
            {
                "caption": "Paris, France",
                "type": "Point",
                "coordinates": [
                    2.3522219000000177,
                    48.856614
                ]
            },
            {
                "caption": "Lyon, France",
                "type": "Point",
                "coordinates": [
                    4.835659,
                    45.764043
                ]
            },
            {
                "caption": "Toulouse, France",
                "type": "Point",
                "coordinates": [
                    1.4442090000000007,
                    43.604652
                ]
            }
        ],
    }

阶段按所需顺序列出(巴黎 - >里昂 - >图卢兹)。 然后我有一个带有两个输入的简单表单(开始结束)。 我的问题是:我怎样才能找到最近的车?

似乎我必须做那样的事情:

找到乘坐地点:

  1. 阶段.X靠近开始
  2. 阶段.Y靠近结束
  3. X< ÿ
  4. 您是否知道如何进行此类查询?

1 个答案:

答案 0 :(得分:0)

我找到了一个奇怪的方法来完成这项工作,这里是:

WM_CONTEXTMENU

计算两点之间距离的函数:

// Set up of arguments and scope
var from =  [2.3522219000000177, 48.856614];
var to =    [4.835659, 45.764043];
var maxDistance = 2000; // in meters

// First, find ids where rides are near my "from" point
var ids = Rides.find({
    stages: {
        $near: {
            $geometry: {
                type: 'Point',
                coordinates: from,
            },
            $maxDistance: maxDistance,
        }
    }
}, {
    fields:{
        _id:1
    }
}).map(function(item){return item._id;});

// Then, find rows which are near my "to" point BUT restricting it to my ids found above
var results = Rides.find({
    _id: {$in: ids},
    stages: {
        $near: {
            $geometry: {
                type: 'Point',
                coordinates: to,
            },
            $maxDistance: maxDistance,
        }
    }
});

// Foreach the rows to filter the case where I match the points in the wrong order
var filtered = [];
results.forEach(function(row){
    var distFrom = [];
    var distTo = [];
    _(row.stages).each(function(stage){
        distFrom.push(calcDistance(stage.coordinates, from));
        distTo.push(calcDistance(stage.coordinates, to));
    });

    var nearestFrom = _.indexOf(distFrom, _.min(distFrom));
    var nearestTo = _.indexOf(distTo, _.min(distTo));

    if(nearestFrom < nearestTo)
        filtered.push(row);
});

// My final results!
console.log(filtered);