嗯,这是我的距离排序点的数组给定点的尝试。据我所知,这是蛮力。然后我给这个数组给你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