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

Limit array of objects in radius and sort by distance

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

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

同样在两个变量中,我正在处理我的中心点和以米为单位的半径

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

我的目标是创建一个函数,该函数将 return 距离中心最大距离为 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 提取到我的项目中以便于对象和数组操作

给你:

    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);