【问题标题】:Sorting multiple JavaScript array对多个 JavaScript 数组进行排序
【发布时间】:2013-01-02 17:51:58
【问题描述】:

我在 Haversine 公式的帮助下创建了这个脚本,问题是它一直将我引导到阵列上的第一个位置,无论我交换它们多少次。有什么想法吗?

var locations = new Array(
  Array("Brighton", 50.82253, -0.137163),
  Array("Chichester", 50.83761, -0.774936),
  Array("Portsmouth", 50.8166667, -1.0833333),
  Array("Worthing", 50.81787, -0.372882)
);

function deg2rad(degrees){
    radians = degrees * (Math.PI/180);
    return radians;
}

function haversine(lat1,lon1,lat2,lon2) {
    deltaLat = lat2 - lat1;
    deltaLon = lon2 - lon1;
    earthRadius = 3959; // In miles (6371 in kilometers)
    alpha = deltaLat/2;
    beta = deltaLon/2;
    a = Math.sin(deg2rad(alpha)) * Math.sin(deg2rad(alpha)) 
      + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) 
      * Math.sin(deg2rad(beta)) * Math.sin(deg2rad(beta));
    c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    distance = earthRadius * c;
    return distance.toFixed(2);
}

function locationSuccess(position) {

    var places = new Array();
    var userLatitude = position.coords.latitude;
    var userLongitude = position.coords.longitude;

    for(var i=0;i<locations.length;i++) {
        places.push(haversine(
          userLatitude,
          userLongitude,
          locations[i][1],
          locations[i][2]
        ));
    }

    var sorted = places.sort(); // Sort places from low to high 

    /*
    alert(places); // Listed distances unordered
    alert(sorted); // Listed distances in order
    alert(sorted[0]); // Nearest city distance
    */

}

function locationFailed() {
    // Change me to a better error message
    alert("Ooops, we couldn't find you!"); 
}

// Get user's physical location
navigator.geolocation.getCurrentPosition(locationSuccess, locationFailed);

【问题讨论】:

    标签: javascript arrays html geolocation haversine


    【解决方案1】:

    您不是对位置数组进行排序,而是对距离数组进行排序。

    您应该将距离放入locations 数组中(即作为每个元素的第四个成员):

    for(var i = 0; i < locations.length; ++i) {
        var l = locations[i];
        l[3] = haversine(userLatitude, userLongitude, l[1], l[2]);
    }
    

    然后使用查看该距离场的“比较器”函数:

    locations.sort(function(a, b) {
        return (a[3] < b[3]) ? -1 : ((a[3] > b[3]) ? 1 : 0);
    });
    

    【讨论】:

    • 我会的。直到 7 分钟过去了,我才能接受它。顺便说一句,你最后一段代码的第 2 行有语法错误。
    猜你喜欢
    • 2022-01-18
    • 2011-10-23
    • 1970-01-01
    • 1970-01-01
    • 2012-11-27
    • 1970-01-01
    • 1970-01-01
    • 2012-10-24
    相关资源
    最近更新 更多