开发者

How to search for "Nearby Users" using mongoid, rails, and google maps

开发者 https://www.devze.com 2023-03-13 13:05 出处:网络
I have a model User with Latitude and Longitude data stored usi开发者_如何转开发ng Mongo DB. I\'m using the google maps javascript api v3 to get this data.

I have a model User with Latitude and Longitude data stored usi开发者_如何转开发ng Mongo DB.

I'm using the google maps javascript api v3 to get this data.

What's the best way to display "Nearby Users"?


Though DhruvPathak answer is correct, here is the equivalent mongoid ruby code for doing geo queries

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

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


Store your data so that it can have geospatial indexing. MongoDb has inbuilt support for this. Then you can easily use inbuilt querying for distance/proximity .

Have a look at :

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)*
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号