Mongoid Geospatial

A Mongoid Extension that simplifies the use of MongoDB spatial features.

Gem Version Code Climate Coverage Status Build Status

Quick Start

This gem focuses on (making helpers for) MongoDB's spatial features using Mongoid 5, 6 and 7.

# Gemfile
gem 'mongoid-geospatial'

A Place to illustrate Point, Line and Polygon

class Place
  include Mongoid::Document

  # Include the module
  include Mongoid::Geospatial

  # Just like mongoid,
  field :name,     type: String

  # define your field, but choose a geometry type:
  field :location, type: Point
  field :route,    type: LineString
  field :area,     type: Polygon

  # To query on your points, don't forget to index:
  # You may use a method:
  sphere_index :location  # 2dsphere
  # or
  spatial_index :location # 2d

  # Or use a helper directly on the `field`:
  field :location, type: Point, spatial: true  # 2d
  # or
  field :location, type: Point, sphere: true   # 2dsphere
end

A pin named geom on a 2dsphere index is one include:

include Mongoid::Geospatial::Geom   # field :geom, type: Point, sphere: true
# or a named one:
geom :pick_up

Generate indexes on MongoDB via rake:

rake db:mongoid:create_indexes

Or programatically:

Place.create_indexes

Points

This gem defines a specific Point class under the Mongoid::Geospatial namespace. Make sure to use type: ::Mongoid::Geospatial::Point to avoid name errors or collisions with other Point classes you might already have defined NameErrors.

Currently, MongoDB supports query operations on 2D points only, so that's what this lib does. All geometries apart from points are just arrays in the database. Here's is how you can input a point as:

  • longitude latitude array in that order - [long,lat] ([x, y])
  • an unordered hash with latitude key(:lat, :latitude) and a longitude key(:lon, :long, :lng, :longitude)
  • an ordered hash with longitude as the first item and latitude as the second item; this hash does not have include the latitude and longitude keys
  • anything with the a method #to_xy or #to_lng_lat that converts itself to [long, lat] array

Note: the convention of having longitude as the first coordinate may vary for other libraries. For instance, Google Maps often refer to "LatLng". Make sure you keep those differences in mind. See below for how to configure this library for LatLng.

We store data in the DB as a [x, y] array then reformat when it is returned to you

cafe = Place.create(
  name: 'Café Rider',
  location: {:lat => 44.106667, :lng => -73.935833},
  # or
  location: {latitude: 40.703056, longitude: -74.026667}
  #...

Now to access this spatial information we can do this

cafe.location  # => [-74.026667, 40.703056]

If you need a hash

cafe.location.to_hsh   # => { x: -74.026667, y: 40.703056 }

Commonly used

cafe.location.to_lat_lon   # => { latitude: 40.703056, longitude: -74.026667 }
cafe.location.lat          # => 40.703056
cafe.location.lng          # => -74.026667
cafe.location.distance(other) # => km, haversine

If you are using GeoRuby or RGeo

cafe.location.to_geo   # => GeoRuby::Point

cafe.location.to_rgeo  # => RGeo::Point

Conventions:

This lib uses #x and #y everywhere. It's shorter than lat or lng or another variation that also confuses. A point is a 2D mathematical notation, longitude/latitude is when you use that notation to map an sphere. In other words: all longitudes are 'xs' where not all 'xs' are longitudes.

Distance is Point#distance (haversine, km). Projections and heavier geometry still go to RGeo or GeoRuby. Some built in helpers for mongoid queries:

# Returns middle point + radius
# Useful to search #within_circle
cafe.location.radius(5)        # [[-74.., 40..], 5]
cafe.location.radius_sphere(5) # [[-74.., 40..], 0.00048..]

# Returns hash if needed
cafe.location.to_hsh              # {:x => -74.., :y => 40..}
cafe.location.to_hsh(:lon, :lat)  # {:lon => -74.., :lat => 40..}

And for polygons and lines:

house.area.bbox    # Returns polygon bounding_box (envelope)
house.area.center  # Returns calculate middle point

Model Setup

You can create Point, Line, Circle, Box and Polygon on your models:

class CrazyGeom
  include Mongoid::Document
  include Mongoid::Geospatial

  field :location,  type: Point, spatial: true, delegate: true

  field :route,     type: Line
  field :area,      type: Polygon

  field :square,    type: Box
  field :around,    type: Circle

  # default mongodb options
  spatial_index :location, {bit: 24, min: -180, max: 180}

  # query by location
  spatial_scope :location
end

Helpers

You can use spatial: true to add a '2d' index automatically, No need for spatial_index :location:

field :location,  type: Point, spatial: true

And you can use sphere: true to add a '2dsphere' index automatically, no need for spatial_sphere :location:

field :location,  type: Point, sphere: true

You can delegate some point methods to the instance itself:

field :location,  type: Point, delegate: true

Now instead of instance.location.x you may call instance.x.

Geometry

You can also store Circle, Box, Line (LineString) and Polygons. Some helper methods are available to them:

# Returns a geometry bounding box
# Useful to query #within_geometry
polygon.bbox
polygon.bounding_box

# Returns a geometry calculated middle point
# Useful to query for #near
polygon.center

# Returns middle point + radius
# Useful to search #within_circle
polygon.radius(5)        # [[1.0, 1.0], 5]
polygon.radius_sphere(5) # [[1.0, 1.0], 0.00048..]

Query

You can use Geometry instance directly on any query:

near

Bar.near(location: person.house)
Bar.where(:location.near => person.house)

near_sphere

Bar.near_sphere(location: person.house)
Bar.where(:location.near_sphere => person.house)

nearby / within

Bar.nearby(person.house)
Bar.nearby(person.house, km: 30)
Bar.within(person.house, 30)          # same question, km required
Bar.nearest(person.house, 30)         # the closest one, or nil
Ride.within(here, 5, field: :drop_up) # two pins? name the one you mean
City.where(:geom.near_sphere => Mongoid::Geospatial.near_query(geom, 50))

within caps by km, nearest first, chainable — on either index. $nearSphere speaks two dialects and the field's index picks which, so the km never moves:

   sphere: true    { loc: { $nearSphere: { $geometry: {..}, $maxDistance: <metres> } } }
   spatial: true   { loc: { $nearSphere: [x, y],            $maxDistance: <radians> } }
                                                                          km / 6371

Hand the server the wrong one and it answers NoQueryExecutionPlans — not a wrong count, a raise.

within(..).first is not the nearest one. Mongoid's #first and #last sort by _id whenever the criteria carries no sort of its own, and that _id sort replaces the distance order $near put there. It reads as working every time the closest document happens to be the oldest. Walk the criteria (.to_a.first) or ask nearest. Mongoid::Geospatial.near_selector(field, point, km, sphere: <bool>) is the one place both shapes are built; near_query is the 2dsphere half of it, for a query you write by hand.

Don't call #first or #last on a $near criteria. Mongoid sorts by _id when a criteria carries no sort of its own, and that replaces the distance order Mongo put there. Walk the criteria instead — .to_a.first — or use geo_near, which returns the distance as a field you can sort on.

You can add a spatial_scope on your models. So you can query:

Bar.nearby(my.location)

instead of

Bar.near(location: my.location)

Good when you're drunk. Just add to your model:

spatial_scope :<field>

geo_near

The geo_near class method provides a more powerful way to query for documents based on proximity, using MongoDB's $geoNear aggregation pipeline stage. This method allows for more complex options and returns the distance to each matched document.

# Find places near [10, 20], using spherical calculations, up to 5km away,
# and get the distance.
# The :distanceField option specifies the name of the field that will contain the distance.
# The :limit option is applied as a separate $limit stage in the aggregation.
Place.geo_near(:location, [10, 20],
               spherical: true,
               maxDistance: 5000, # 5 kilometers in meters for spherical queries
               distanceField: 'dist.calculated', # Default is 'distance'
               query: { category: 'restaurant' }, # Optional: filter documents before geoNear
               limit: 10)

# Iterate over results — HASHES, not documents. Nothing is instantiated:
# $geoNear adds fields a model has no field for.
Place.geo_near(:location, [10, 20], spherical: true).each do |doc|
  puts "#{doc['name']} is #{doc['distance']} meters away."
end

# Want models? ask for them at the call site:
Place.geo_near(:location, [10, 20]).map { |attrs| Place.instantiate(attrs) }

Key features and options for geo_near:

  • :spherical (Boolean): If true, calculates distances using spherical geometry. Defaults to false.
  • :distanceField (String): Name of the output field for the calculated distance. Defaults to 'distance'.
  • :maxDistance (Numeric): Maximum distance from the center point. (Meters for spherical, units of coordinates for planar).
  • :minDistance (Numeric): Minimum distance from the center point.
  • :query (Hash): A query to filter documents before the $geoNear stage.
  • :limit (Integer): Maximum number of documents to return (applied as a separate $limit stage).
  • :distanceMultiplier (Numeric): A factor to multiply all distances.
  • :includeLocs (String): Name of an output field that will contain the exact location on the document used for the distance calculation. Useful for multi-location fields or complex GeoJSON geometries.

The geo_near method returns an array of instantiated Mongoid documents, with the distanceField and includeLocs field (if specified) available as dynamic attributes on each model instance.

  • within_polygon
Bar.within_polygon(location: [[[x,y],...[x,y]]])
# or with a bbox
Bar.within_polygon(location: street.bbox)
  • within_circle / within_spherical_circle

Mongoid ships within_polygon and within_box and stopped there; this gem registers the two circle shapes, which is what radius and radius_sphere have been building arguments for all along.

Bar.where(:location.within_spherical_circle => cafe.location.radius_sphere(5, :km))
Bar.where(:location.within_circle => cafe.location.radius(0.05))  # degrees, flat

$centerSphere reads radians (radius_sphere hands it those); $center reads the coordinate system's own units — degrees on a legacy pair.

  • intersects_line
  • intersects_point
  • intersects_polygon

External Libraries

We currently support GeoRuby and RGeo. If you require one of those, a #to_geo and #to_rgeo, respectivelly, method(s) will be available to all spatial fields, returning the external library corresponding object.

Use RGeo?

https://github.com/dazuma/rgeo

RGeo is a Ruby wrapper for Proj/GEOS. It's perfect when you need to work with complex calculations and projections. It'll require more stuff installed to compile/work.

Use GeoRuby?

https://github.com/nofxx/georuby

GeoRuby is a pure Ruby Geometry Library. It's perfect if you want simple calculations and/or keep your stack in pure ruby. Albeit not full featured in maths it has a handful of methods and good import/export helpers.

Example

class Person
  include Mongoid::Document
  include Mongoid::Geospatial

  field :location, type: Point
end

me = Person.new(location: [8, 8])

# Example with GeoRuby
point.class # Mongoid::Geospatial::Point
point.to_geo.class # GeoRuby::SimpleFeatures::Point

# Example with RGeo
point.class # Mongoid::Geospatial::Point
point.to_rgeo.class # RGeo::Geographic::SphericalPointImpl

Configure

Assemble it as you need (use a initializer file):

With RGeo

Mongoid::Geospatial.with_rgeo!
# Optional
# Mongoid::Geospatial.factory = RGeo::Geographic.spherical_factory

With GeoRuby

Mongoid::Geospatial.with_georuby!

By default the convention of this library is LngLat, configure it for LatLng as follows.

Mongoid::Geospatial.configure do |config|
  config.point.x = Mongoid::Geospatial.lat_symbols
  config.point.y = Mongoid::Geospatial.lng_symbols
end

You will need to manually migrate any existing Point data if you change configuration in an existing system.

This Fork

This fork is not backwards compatible with 'mongoid_spacial'. This fork delegates calculations to external libs.

Change in your models:

include Mongoid::Spacial::Document

to

include Mongoid::Geospatial

And for the fields:

field :source,  type: Array,    spacial: true

to

field :source,  type: Point,    spatial: true # or sphere: true

Beware the 't' and 'c' issue. It's spaTial.

Troubleshooting

Mongo::OperationFailure: can't find special index: 2d

Indexes need to be created. Execute command:

rake db:mongoid:create_indexes

Programatically

Model.create_indexes

Contributing

See CONTRIBUTING.

License

Copyright (c) 2009-2017 Mongoid Geospatial Authors

MIT License, see MIT-LICENSE.