ruby-on-railsrubygeosrgeo

Point in polygon rgeo


I need to know if a point is in a polygon or not, in my rails app, in order to to that I wan to use rgeo gem.

To install this geme i folowed the instructions on rgeo git

Then I'm sure that GEOS and Proj4 are properly installed.

enter image description here

I also added this gem 'ffi-geos', no particular reason, only following rgeo doc

Finally I made a test on rails console to check if is working

  1. poly_text = "POLYGON ..." (a lot of points, I'm aware that the first point and the last one are the same, otherwise I think this wount work because needs to be a closed polygon)
  2. factory = RGeo::Cartesian::Factory (I'm using a cartesian factory because acording to my investigation, if I use a spheric one, this wount work)
  3. poly = factory.new().parse_wkt(poly_text)
  4. point1 = factory.new().parse_wkt("POINT (0 0)") (this point does not belong to the polygon)
  5. poly.within?(point1)
  6. result: RGeo::Error::UnsupportedOperation: Method Geometry#contains? not defined. from (irb):26

here you can see the output: enter image description here

More info: rails version 5.1.2 ide c9 os ubuntu

if someone has a solution, thanks in advance, I'm also open to use another gem, or whatever, my goal is to solve my point / polygon problem.


Solution

  • You could use Geokit, just include gem 'geokit' in your Gemfile.

    Then you will need to create an array of points, where each point is a Geokit::LatLng.

    For example:

    points = []
    points << Geokit::LatLng.new("-34.8922513", "-56.1468951")
    points << Geokit::LatLng.new("-34.905204", "-56.1848322")
    points << Geokit::LatLng.new("-34.9091105", "-56.170756")
    polygon = Geokit::Polygon.new(points)
    polygon.contains? polygon.centroid #this should return true
    

    Don't worry about whether or not the first point is the same as the last, the new already takes care of that as it is explained here in the source code.