如何找到我周围最近的10个位置。我们说我的当前纬度,经度和我周围位置的坐标
我有:
var myLatitude = 00000.0000;
var myLongitude = 0000.0000;
var worldAroundMe = [{ 'lat': something,'long': something, }, {'latitude': something,'longitude': something,}{more locations}];
答案 0 :(得分:4)
您想要计算从每个坐标到纬度/经度的距离,然后按该数字排序:
function sortByDistance(myLatitude, myLongitude, world) {
var distances = []; // This will hold an array of objects. Each object will have two keys: distance, and place. The distance will be the distance of the place from the given latitude and longitude
// Find the distance from each place in the world
for (var i = 0; i < world.length; i++) {
var place = world[i];
var distance = Math.sqrt(Math.pow(myLatitude - place.latitude, 2) + Math.pow(myLongitude - place.longitude, 2)); // Uses Euclidean distance
distances.push({distance: distance, place: place});
}
// Return the distances, sorted
return distances.sort(function(a, b) {
return a.distance - b.distance; // Switch the order of this subtraction to sort the other way
})
.slice(0, 10); // Gets the first ten places, according to their distance
}
请注意,这是使用欧几里德距离https://en.wikipedia.org/wiki/Euclidean_distance。还有其他确定距离的方法可能更适合您的应用。
另请注意,这是执行O(n)
操作(假设您的JavaScript引擎正在排序最多O(n)
复杂度的数组; Google&#34; Complexity Classes&#34;以了解{ {1}}意味着),因此,1000倍的地方数量会慢1000倍。尽管如此,优化方法还包括:
O(?)