[GIS] Searching for polygons which have certain location using MongoDB

mongodbpoint-in-polygon

I am trying to implement a search feature on MongoDB using Mongoose.js , the short version of which is this:

I tag locations on a map as polygons. and give them names. Then when an user searches for a place using coordinates, I check which polygon the location falls within, and return the polygon.

I know that the reverse of what I am trying to do works by specifying a polygon, and then searching for locations which fall within the polygon, but I am looking for the opposite.

So instead of saying:

var polyA = [ [ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ] ]
query.where('loc').within.polygon(polyA)

I want to say

var 'loc' = [ 11, 24 ]
query.where(loc).within.polygon('polygon')

where 'polygon' is a polygon schema.

I believe it might be possible to do this with mongoDB 2.4 as it'll support GeoJSON, but is it currently possible to do it with mongoDB 2.2?

What I've thought of so far

I think it might not be possible even with MongoDB 2.4. So I'm thinking of using some linear algebra to solve this.

  1. I compute the center of the polygon, and store it with the polygon area.
  2. Then when I search the database I find a polygon with the center/area-point within a certain distance of the location.
  3. Loop through each two points in the polygon, and set an y <?> m(x) + c type constraint, store the constraints in a JavaScript object.
  4. Check if location coordinates satisfy the constraints, and return false if any of them is not satisfied. Else return true if satisfied.

In effect I'm drawing a polygon's restrictions, and checking if the said location meets all of these. The problem here's that if I have complex polygons (which I'll more likely have) the test would take longer to return an answer.

On reinventing the wheel

I sometimes get reprimanded for 'reinventing the wheel' by using MongoDB instead of a proper GIS database, which normally has some of the features I ask about. I am aware that what I am trying to do is what has probably been solved years ago by RMDBS, but I want to do it in Mongo.
One prevalent way which this feature is likely already implemented is in geocoding, because to find the town/state/country which a point lies in, one would do the above. I thus sincerely want to try to do this in MongoDB as it complements the other computations that I'm already performing in Mongo.

Best Answer

MongoDB 2.4 has support for this, so I ended up upgrading. The documentation was not very clear at the time (during pre-release), but the feature works using $geoWithin on Polygon GeoJSON objects.

Related Question