Store GeoJSON polygons in MongoDB

亡梦爱人 提交于 2019-12-03 03:52:25

It seems that mongo 2.3.2 development release now has GeoJSON support: Release Notes for MongoDB 2.4

With MongoDB 2.4 use the "2dsphere" index for GeoJSON Points, LineStrings and Polygons.

For example, you can create this index:

db.mycoll.ensureIndex( { loc : "2dsphere" } )

And store this LineString:

{ loc : { type : "LineString" , coordinates : [ [ 1 , 2 ] , [ 3 , 4 ] ] } }

See http://docs.mongodb.org/manual/applications/2dsphere/.

I had to do this same thing myself to set up a GeoFence feature. What I did was store "polygon" data as a series of coordinate, and a center. For instance:

{ 
    "_id" : ObjectId( "4f189d132ae5e92272000000" ),
    "name" : "Alaska",
    "points" : [ 
        { "coords" : [ 
            -141.0205, 
            70.0187 ] 
        }, 

        ...

        { "coords" : [ 
            -141.0205, 
            70.0187 ] 
        } 
    ],
    "center" : { 
        "coords" : [ 
          -153.6370465116279, 
          61.42329302325581 ] 
    } 
}

In my application (in python) I am using the shapely library. What I first do is find a list of objects that have a center closest to my point. Then on the client side (python) I use shapely convert each large coordinate array to a polygon, and then test the regions to find which ones contain my point.

So you can store polygon data in MongoDB as just data, and use some other precomputed 2d index like a center.

Give this a try from the mongo shell:

// Polygon in GeoJson format
var poly = {};
poly.name = 'GeoJson polygon';
poly.geo = {};
poly.geo.type = 'Polygon';
poly.geo.coordinates = [
    [ [ -80.0, 30.0 ], [ -40.0, 30.0 ], [ -40.0, 60.0 ], [-80.0, 60.0 ], [ -80.0, 30.0 ] ]
];
db.foo.insert(poly);
db.foo.ensureIndex({geo: "2dsphere" });

MongoDB's geospatial features currently only support storing points, not shapes or lines. You are however able to query for points using circles, rectangles, or polygons.

Based on the MongoDB documentation here, a polygon could be stored as a GeoJSON polygon like:

{
  type: "Polygon",
  coordinates: [ [ [ 0 , 0 ] , [ 3 , 6 ] , [ 6 , 1 ] , [ 0 , 0  ] ] ]
}

It's a simple one with a simple ring but it's also possible to store a polygon with multiple rings.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!