Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb : Check if a point is inside a stored polygon

Tags:

I'm new to the mongodb geolocation features.

I stored some polygons that represent the country borders in a database along with the country name. Now what i would like to do is checking which country a point is in. For example if i give my own geolocation i would like to get the country where i am.

Is there a way to do it with mongodb? Maybe with geoWithin?

Thank you

like image 775
SkinyMonkey Avatar asked Apr 07 '13 18:04

SkinyMonkey


2 Answers

You must store your location data like this schema:

{"loc":
     {"coordinates":[
       [
         [1.0,1.0],
         [1.0,10.0],
         [10.0,10.0],
         [10.0,1.0],
         [1.0,1.0]
       ]
      ],
     "type":"Polygon"
   }
}

and then send $geoIntersects queries

db.polygons.find({"loc":{"$geoIntersects":{"$geometry":{"type":"Point", "coordinates":[x, y]}}}}
like image 98
David Chaava Avatar answered Sep 19 '22 03:09

David Chaava


You have to use $geoIntersects for that.

db.features.find({mystoredpolygon:{$geoIntersects:{$geometry:{type:'Point', coordinates:[22,38]}}}})
like image 23
gtsouk Avatar answered Sep 22 '22 03:09

gtsouk