如何使用mongoid,rails和google地图搜索“Nearby Users”

时间:2011-06-16 03:43:59

标签: ruby-on-rails google-maps mongodb geolocation mongoid

我有一个模型用户,使用Mongo DB存储纬度和经度数据。

我正在使用谷歌地图javascript api v3获取此数据。

显示“附近用户”的最佳方式是什么?

2 个答案:

答案 0 :(得分:1)

存储您的数据,以便它可以进行地理空间索引。 MongoDb已经内置了对此的支持。然后,您可以轻松地使用内置查询 距离/接近度。

看看:

http://www.mongodb.org/display/DOCS/Geospatial+Indexing

*Querying

The index can be used for exact matches:

db.places.find( { loc : [50,50] } )

Of course, that is not very interesting. More important is a query to find points near another point, but not necessarily matching exactly:

db.places.find( { loc : { $near : [50,50] } } )

The above query finds the closest points to (50,50) and returns them sorted by distance (there is no need for an additional sort parameter). Use limit() to specify a maximum number of points to return (a default limit of 100 applies if unspecified):

db.places.find( { loc : { $near : [50,50] } } ).limit(20)

You can also use $near with a maximum distance

db.places.find( { loc : { $near : [50,50] , $maxDistance : 5 } } ).limit(20)*

答案 1 :(得分:1)

虽然DhruvPathak的答案是正确的,但这里是用于进行地理查询的等效mongoid ruby​​代码

User.where(:loc => {'$near' => [50,50]})

User.where(:loc => {'$near' => [50,50],'$maxDistance' => 5})