Mongodb with Mongoid in Rails - Geospatial Indexing

MongoDB with Mongoid in Rails - Geospatial Indexing

You can define geo indexes like this in mongoid

class Item
include Mongoid::Document

field :loc, :type => Array

index(
[
[:loc, Mongo::GEO2D]
], background: true

)
end

And for queries

$near command (without maxDistance)

 location = [80.24958300000003, 13.060422]
items = Item.where(:loc => {"$near" => location})

$near command (with maxDistance)

 distance = 10 #km
location = [80.24958300000003, 13.060422]
items = Item.where(:loc => {"$near" => location , '$maxDistance' => distance.fdiv(111.12)})

Convert distance by 111.12 (one degree is approximately 111.12 kilometers) when using km, or leave distance as it is on using degree

$centerSphere / $nearSphere queries

location = [80.24958300000003, 13.060422]
items = Item.where(:loc => {"$within" => {"$centerSphere" => [location, (distance.fdiv(6371) )]}})

This will find the items within the 10 km radius. Here we need to convert the distance/6371(earth radius) to get it work with km.

$box (bounding box queries)

 first_loc = [80.24958300000003, 13.060422]
second_loc = [81.24958300000003, 12.060422]
items = Item.where(:loc => {"$within" => {"$box" => [first_loc, second_loc]}})

This will help you to find the items within the given bounding box.

Using geoNear with Rails / Mongoid

You don't need the mongoid_geospatial gem to do a geoNear query: mongoid already supports it (in version 3 at least).

Change your model to:

class Company
include Mongoid::Document
include Mongoid::Timestamps

field :name, type: String

field :location, type: Array

index({location: "2d"})

validates :location, location: true
end

And run your query as:

@vendors = Vendor.geo_near([-2.1294761000000335,57.0507625]).max_distance(5)

Mongoid, Can not find models by geospatial calculation

I have found solution. I just simply forgot to run indexing rake task.

What's the best tutorial for doing geospatial queries with Rails/Mongoid?

The MongoDB documentation for geospatial indexing is available here. That should provide you with details on "how to store and query location data".

mongoid is just an object wrapper around the existing Ruby driver. Once you understand how to issue geo queries, then it should just be a matter of issuing these queries via mongoid.

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

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})


Related Topics



Leave a reply



Submit