2014-02-26 42 views
3

我有一個MongoDB的集合與地理指標:計算距離MongoDB中的map-reduce

> db.coll.getIndexes() 
[ 
    // ... 
    { 
     "v" : 1, 
     "key" : { 
      "location" : "2dsphere" 
     }, 
     "ns" : "test.coll", 
     "dropDups" : false, 
     "name" : "location_2dsphere", 
     "background" : false 
    } 
] 

db.coll.findOne({location: {'$exists': true}}, {'location': 1}) 
{ 
    "_id" : ObjectId("52cd72ae2ac170aa3eaace6e"), 
    "location" : [ 
     55.4545177559, 
     11.5767419669 
    ] 
} 

在這我跑地圖降低,這看起來是這樣的:

var map = function() { 
    var value = 0; 

    // ... various calculations on the value here 

    var distance = 0; // < This is the problematic part 
    if (distance < 1000) { 
     val += distance; // for example 
    } 

    emit(this._id, value) 
} 
var reduce = function(id, val) { 
    return {id: val} 
} 

db.coll.mapReduce(map, reduce, {out: {inline: 1}}) 

是有一種方法來計算location和X點之間的距離,在map函數中?

我正在尋找類似$geoNear的東西,但與map-reduce有某種結合。

例如:

db.runCommand({geoNear: "coll", near: [-74, 40.74], spherical: true}) 

返回每個文件的距離。但我找不到一種方法將其與map-reduce命令結合使用。

+0

http://www.movable-type.co.uk/scripts/latlong.html – Andy

+0

此外,你有什麼已經嘗試過? – Andy

+0

在純js中做它並不是最理想的,因爲mongo已經支持距離計算... – yprez

回答

4

大圓公式是去http://en.wikipedia.org/wiki/Great-circle_distance

我跑了與蒙戈和JS類似的問題的方式。並提出了這個功能。希望能幫助到你。

function find(point, latlng, radius){ 
     var dist = parseInt(radius) * 0.868976/60; // convert miles to rad 

    if((point[0] <= latlng[0] + dist && point[1] >= latlng[1]- dist) 
    && (point[0] <= latlng[0]+ dist && point[1] >= latlng[1]- dist)){ 

     dx = latlng[0] - point[0]; 
     dy = latlng[1] - point[1]; 
     dx *= dx; 
     dy *= dy; 
     ds = dx + dy; 
     rs = dist * dist; 
     is = ds <= rs; 

     return is; 
    } 
} 

林調用該是這樣的:

find([-79,5], [40,20], 5); 
+1

好,謝謝!我已經用另一種方式解決了它(用Python代替距離計算),但這似乎是一個很好的解決方案。 – yprez

1

我知道這是一個晚此外,但來這裏的其他人也可能是很好的瞭解套件,可用於做的JavaScript庫地理相關功能。

https://github.com/manuelbieh/Geolib