Search code examples
ruby-on-railsrgeo

Calculating Polygon area using RGeo in Ruby on Rails


Starting from a model called Field that contains a column called "polygon" (Cartesian coordinates as an array), I want to calculate the area in hectares with RGeo:

class Field < ApplicationRecord
  def area
    factory = RGeo::Cartesian.factory(srid: 4326)
    polygon = factory.polygon(self.polygon)
    polygon.area
  end
end

Unfortunately, I always get this error message:

NoMethodError (undefined method `factory' for #<Array:0x0000aaaac742b9a0>)

I'm using rgeo 3.0.0


Solution

  • It sounds like you are passing your factory an array of points (themselves arrays of integers?), but the rgeo documentation specifies a different way that the argument to #polygon should be prepared:

    pt1 = factory.point(1, 1, 1)
    pt2 = factory.point(1, 2, 1)
    pt3 = factory.point(2, 2, 1)
    pt4 = factory.point(2, 1, 1)
    
    ring = factory.linear_ring([pt1, pt2, pt3, pt4, pt1])
    polygon = factory.polygon(ring)
    
    p polygon.area
    # => 1.0
    

    If self.polygon does indeed return an array of arrays of integers, then you could use something like

    points = self.polygon.map { |point| factory.point(*point) }
    ring = factory.linear_ring(points)
    polygon = factory.polygon(ring)