你要计算从每个距离坐标与纬度/经度,然后排序由该数字:
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)
复杂的阵列;谷歌“复杂性类”学什么O(?)
手段),因此这将是慢1000倍地点数量的1000倍。方法尽管如此优化包括:
- 缓存的结果,使这一计算并没有做不止一次
- 有距离为(例如
{latitude: 123, longitude: 321, distance: 543}
的“地方”对象的一部分被计算仅当对象被创建
这里的正在使用它的一个例子(在谷歌浏览器的开发者控制台):