David Graça
David Graça

Reputation: 333

Mongodb: How can I check if a point is contained in a polygon?

I've got a list of points of a area in an array of points (latitude, longitude). I 've made an index on these arrays and now I want to know if one point is inside that polygon.

Is it possible with MongoDB? I already tried with these commands but no luck:

 > polygonA = [ [ 48.780809,2.307129],[ 48.781809,2.300129],[ 48.770809,2.317129]]
 > db.contours.find({ "rings.ring" : { "$within" : { "$polygon" : polygonA } } })

and

 > db.runCommand( { geoNear : "contours" , within : [2.307129,48.780809,], num : 10 } );

My data structure is:

 > db.contours.findOne({},{'rings':0})
 {
         "_id" : ObjectId("50364617d591ac166000c196"),
         "foundfieldname" : "Name",
         "geometrytype" : "geometryPolygon",
         "attributes" : {
                 "Shape" : "Polygon",
                 "Name" : "France",
                 "Type" : "Country",
                 "Country" : "France",
                 "Area" : "1162358716567.45"
         },
         "country" : "France",
 "rings":{
      "ring":[[12.32,43.54],...],
           ...
 }

Thanks

Upvotes: 3

Views: 2119

Answers (1)

Adam Comerford
Adam Comerford

Reputation: 21692

This requires that rings.ring be a points and that it have a geo index defined on it, is that the case here?

Your question implies that this is in fact a list of multiple points with a standard index on it (multikey index), which is not going to work.

http://www.mongodb.org/display/DOCS/Geospatial+Indexing/#GeospatialIndexing-BoundsQueries

As you can see there, when you search for "loc" as a point inside a polygon, the "loc" field is something like this (see the link above for other valid examples):

{ loc : [ 50 , 30 ] }

With an index something like this:

db.places.ensureIndex( { loc : "2d" }

That is, a field representing a single point and with a geo index defined on it. If you use a field like that - does your testing then work?

Upvotes: 2

Related Questions