嗯,這是我的距離排序點的數組給定點的嘗試。據我所知,這是蠻力。然後我給這個數組給你10個最近的點。
的Javascript
function distanceBetweenPoints(p1, p2) {
return Math.abs(Math.sqrt((p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1])));
}
function sortByDistance(location, arrayOfPoints) {
arrayOfPoints.sort(function (a, b) {
a.distance = distanceBetweenPoints(location, a);
b.distance = distanceBetweenPoints(location, b);
return a.distance - b.distance;
});
return arrayOfPoints;
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var points = [];
for (i = 0; i < 100; i += 1) {
points.push([getRandomInt(-90, 90), getRandomInt(-180, 180)]);
}
console.log(sortByDistance([0, 0], points).slice(0, 10));
在jsFiddle
這將至少給你的東西來測試算法反對。以上是jsPerf,因此您可以添加其他例程並進行一些真正的性能比較。
注意:這並沒有考慮到地球是一個球體!這是計算Euclidean distance
而不是測地距離。如果這些點例如位於同一個城鎮(或者很接近),但是如果它們位於不同的國家/大陸,則沒有問題。它還假定您已將經度和緯度轉換爲十進制表示。
否則,你就需要看的東西像Great-circle distance
和Haversine formula
事實上,地球是非常輕微的橢圓形;使用球形模型給出了錯誤通常高達0.3%
的Javascript
function toRadians(degrees) {
return (degrees * Math.PI)/180;
}
// Haversine formula
function distanceBetweenPoints(p1, p2) {
var R = 6371, // mean earth radius in km
lat1 = toRadians(p1[0]),
lon1 = toRadians(p1[1]),
lat2 = toRadians(p2[0]),
lon2 = toRadians(p2[1]),
dLat = lat2 - lat1,
dLon = lon2 - lon1,
a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2),
c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)),
d = R * c;
return d;
}
function sortByDistance(location, arrayOfPoints) {
arrayOfPoints.sort(function (a, b) {
a.distance = distanceBetweenPoints(location, a);
b.distance = distanceBetweenPoints(location, b);
return a.distance - b.distance;
});
return arrayOfPoints;
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var points = [];
for (i = 0; i < 100; i += 1) {
points.push([getRandomInt(-90, 90), getRandomInt(-180, 180)]);
}
console.log(sortByDistance([0, 0], points).slice(0, 10));
在jsFiddle
約100個點,這是不可能的,你會看到很多,如果有的話,「分的利益,征服「方法而不是」天真(蠻力)「方法。天真的方法很容易實現。 – Xotic750
它實際上是使用Titanium的移動應用程序。必須做更多的挖掘才能知道爲什麼現在似乎是這樣一個瓶頸......但是無論如何,如果它不是太困難,而不是蠻橫暴力,我想找到最佳解決方案。 – Luke
根據我的理解,「分而治之」的方法是最優的O(n log n) - 取決於排序算法(我認爲需要合併排序) – Xotic750