mongodb check if point is in polygon

前端 未结 2 704
慢半拍i
慢半拍i 2020-12-13 19:52

mongo 2.6

I have some amount of stored polygons. And I have a point. I what to know if this point fits any of stored polygons

document example

相关标签:
2条回答
  • 2020-12-13 20:04

    Thanks for John Powell here is C# driver version of the same query.

     var geometry = new BsonDocument
                                {
                                         { "type", "Point" },
                                         { "coordinates",
                                            new BsonArray(new double[]{ Longitude,
                                            Latitude} ) }
                                };
                        var geometryOperator = new BsonDocument { { "$geometry", geometry } };
                        var geoIntersectsOperator = new BsonDocument { { "$geoIntersects", geometryOperator } };
    
                        var findField = new BsonDocument { { "geometry", geoIntersectsOperator } };
    
    
                        var results = MyCollection.Find(findField).ToList();
    
    0 讨论(0)
  • 2020-12-13 20:11

    It seems to be to do with the order. If you are using $geoWithin and you are trying to find points inside a polygon, the thing that is within is the field you are searching on. However, geoIntersects works in either direction, so you can search for points inside polygons, or polygons containing points, eg,

    db.geom.insert({"polygons":
                          {"type":"Polygon",
                             coordinates:
                              [[[ 17.60083012593064, 78.18557739257812], 
                                [ 17.16834652544664, 78.19381713867188], 
                                [ 17.17490690610013, 78.739013671875], 
                                [ 17.613919673106714, 78.73489379882812],
                                [ 17.60083012593064, 78.18557739257812]
                              ]]
                          }
                     }); 
    
    db.geom.find({polygons:
                     {$geoIntersects:
                         {$geometry:{ "type" : "Point",
                              "coordinates" : [ 17.3734, 78.4738 ] }
                          }
                      }
                 });
    

    Also, note that, you need to repeat the first point of the polygon at the end. If you remove the final pair, you will get a "$err" : "Can't canonicalize query: BadValue bad geo query" error.

    It seems that MongoDB allows you to insert invalid geometries and only complains when you try and add a 2dsphere index or do an intersects/within/near query, which, I suppose is reasonable, as GeoJSON can be valid JSON without being a valid geometry.

    0 讨论(0)
提交回复
热议问题