2015-10-17 186 views
-1

我怎樣才能找到我周圍最近的10個位置。比方說,我有我的當前的緯度,經度和位置我周圍的座標如何找到我附近的最近的10個位置

我:

var myLatitude = 00000.0000; 
var myLongitude = 0000.0000; 
var worldAroundMe = [{ 'lat': something,'long': something, }, {'latitude': something,'longitude': something,}{more locations}]; 

回答

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)複雜的陣列;谷歌「複雜性類」學什麼O(?)手段),因此這將是慢1000倍地點數量的1000倍。方法儘管如此優化包括:

  • 緩存的結果,使這一計算並沒有做不止一次
  • 有距離爲(例如{latitude: 123, longitude: 321, distance: 543}的「地方」對象的一部分被計算僅當對象被創建

這裏的正在使用它的一個例子(在谷歌瀏覽器的開發者控制檯): enter image description here