1

可能重复:
如何对 javascript 对象数组进行排序?

好吧,更准确地说,我有以下课程:

function Location(name, latitude, longitude){
this.latitude = latitude;
this.longitude = longitude;
this.name = name;
}

而且我想按与给定位置(像这样的类的对象)的接近顺序对这些对象的数组进行排序。

4

5 回答 5

7

您需要一个比较器功能:

function sortLocations(locations, lat, lng) {
  function dist(l) {
    return (l.latitude - lat) * (l.latitude - lat) +
      (l.longitude - lng) * (l.longitude - lng);
  }

  locations.sort(function(l1, l2) {
    return dist(l1) - dist(l2);
  });
}

我不关心那里的平方根,因为我认为没有必要。此外,我没有考虑球面几何的任何奇怪之处,因为我再次认为这不值得复杂。但是,如果您有自己的现有方法来计算距离,则可以插入它而不是我上面键入的内容。

您只需将数组以及参考点坐标传递给该函数即可调用它。如果您想传递“位置”实例,则应该清楚要更改的内容。

于 2012-06-05T23:29:29.463 回答
4

请参阅:对 JavaScript 对象数组进行排序

另一个答案的简单 lat1-lat2 + lon1-lon2 公式即使对于数学二维平面也不正确,对于椭球地球更是如此。除非距离真的不需要准确,否则您应该使用半正弦公式作为排序函数。

来自:http ://www.movable-type.co.uk/scripts/latlong.html

var R = 6371; // km
var dLat = (lat2-lat1).toRad();
var dLon = (lon2-lon1).toRad();
var lat1 = lat1.toRad();
var lat2 = lat2.toRad();

var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); 
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
var d = R * c;
于 2012-06-05T23:29:53.753 回答
1

您想将函数传递给Array.prototype.sort. 这个链接有一个很好的解释。我知道这不适用于球面几何,但你会想要这样的东西:

var home = new Location("Home", 40, -50);
arr.sort(function(a, b){
    var dist1 = Math.sqrt(Math.pow(home.latitude-a.latitude, 2) + Math.pow(home.longitude-a.longitude, 2)),
        dist2 = Math.sqrt(Math.pow(home.latitude-b.latitude, 2) + Math.pow(home.longitude-b.longitude, 2));
    if (dist1 < dist2) { 
        return -1;
    }
    else {
        return 1;
    }
});
于 2012-06-05T23:28:09.113 回答
1
function Location(name, latitude, longitude){
this.latitude = latitude;
this.longitude = longitude;
this.name = name;
};

this.locations.push(new Location());

 this.locations.sort(function (a, b) { return a.latitude - b.latitude ; });

您需要将您的位置存储在一个数组中。

于 2012-06-05T23:31:12.180 回答
1
Location.distance = function ( loc1, loc2 ) {
    return Math.sqrt(
        Math.pow( loc2.longitude - loc1.longitude, 2 ) +
        Math.pow( loc2.latitude - loc1.latitude, 2 )
    );
};

Location.prototype.sortByProximity = function ( arr ) {
    var that = this;
    arr.sort(function ( a, b ) {
        return Location.distance( that, a ) - Location.distance( that, b );
    });
};

首先,您有一个静态函数Location.distance,它接受两个Location实例并返回一个表示它们相对距离的值。

其次,您有一个sortByProximity方法,该方法作为Location实例上的方法调用,并且需要一个Location实例数组作为其第一个参数。

用法:

baseLocation.sortByProximity( locArr );
// locArr is now sorted in regard to baseLocation

现场演示:http: //jsfiddle.net/hGp66/

于 2012-06-05T23:40:01.660 回答