限制半径中的对象数组并按距离排序

时间:2015-01-04 18:12:55

标签: javascript node.js underscore.js geospatial

在node.js中,一个对象数组包含一些具有特定格式的坐标

{name:"samplename",location:[longtitude , latitude] }

同样在两个变量中,我正在抚摸我的中心点和半径(米)

var center =[ 12 , -4.32 ]; var radius = 30000;

我的目标是创建一个能够返回距离中心最远距离30000米的所有景点的功能。

给出的输入数据示例

var spots=[
    {name :"spot1",location:[113,32.21] } ,
    {name :"spot2",location:[112,-32.21] } ,
    {name :"spot3",location:[-33,32.11] } ,
    {name :"spot4",location:[113.4,35.21] } ,
    {name :"spot5",location:[11,31.21] }
];
var center =[ 12 , -4.32 ]; var radius = 30000;
var finalspots = Calculatedistance(spots, center, radius)

示例输出

{name :"spot2",location:[112,-32.21], distance:300 } ,
{name :"spot1",location:[113,32.21] , distance:1400 } ,
{name :"spot5",location:[11,31.21], distance:5000 }

P.S我已经将Underscore.js提取到我的项目中以便于对象和数组操作

1 个答案:

答案 0 :(得分:1)

你走了:



    function distanceInMeters (lat1, lon1, lat2, lon2) {
        var R = 6371;
        var f1 = lat1 * Math.PI / 180;
        var f2 = lat2 * Math.PI / 180;
        var dlat = (lat2 - lat1) * Math.PI / 180;
        var dlon = (lon2 - lon1) * Math.PI / 180;
    
        var a = Math.sin(dlat / 2) * Math.sin(dlat / 2) +
            Math.cos(f1) * Math.cos(f2) *
            Math.sin(dlon / 2) * Math.sin(dlon / 2);
    
        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        var d = Math.round(R * c * 1000);
    
        return d;
    }
    
    function sortCallback (a, b) {
        if (a.distance < b.distance)
            return -1;
        if (a.distance > b.distance)
            return 1;
        return 0;
    }
    
    function Calculatedistance (spots, center, radius) {
        var filteredSpots = [];
        for (var i = 0; i < spots.length; i++) {
            var spot = spots[i];
            var distance = distanceInMeters(center[0], center[1], spot.location[0], spot.location[1]);
            if (distance < radius) {
                spot.distance = distance;
                filteredSpots.push(spot);
            }
        }
    
        var sortedSpots = filteredSpots.sort(sortCallback);
    
        return sortedSpots;
    }
    
    var spots = [
        {name: "spot1", location: [113, 32.21]},
        {name: "spot2", location: [112, -32.21]},
        {name: "spot3", location: [-33, 32.11]},
        {name: "spot4", location: [113.4, 35.21]},
        {name: "spot5", location: [11, 31.21]}
    ];
    
    var center = [12, -4.32];
    var radius = 10746486;
    
    var finalspots = Calculatedistance(spots, center, radius);

    console.log(finalspots);
&#13;
&#13;
&#13;