Class: Geokit::Polygon

Inherits:
Object show all
Defined in:
lib/geokit/polygon.rb

Overview

A complex polygon made of multiple points. End point must equal start point to close the poly.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(points) ⇒ Polygon

Pass in an array of Geokit::LatLng



7
8
9
10
11
12
13
# File 'lib/geokit/polygon.rb', line 7

def initialize(points)
  @points = points

  # A Polygon must be 'closed', the last point equal to the first point
  # Append the first point to the array to close the polygon
  @points << points[0] if points[0] != points[-1]
end

Instance Attribute Details

#pointsObject

Returns the value of attribute points.



4
5
6
# File 'lib/geokit/polygon.rb', line 4

def points
  @points
end

Instance Method Details

#centroidObject

A polygon is static and can not be updated with new points, as a result calculate the centroid once and store it when requested.



41
42
43
# File 'lib/geokit/polygon.rb', line 41

def centroid
  @centroid ||= calculate_centroid
end

#contains?(point) ⇒ Boolean

Returns:

  • (Boolean)


15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/geokit/polygon.rb', line 15

def contains?(point)
  last_point = @points[-1]
  oddNodes = false
  x = point.lng
  y = point.lat

  for p in @points
    yi = p.lat
    xi = p.lng
    yj = last_point.lat
    xj = last_point.lng
    if (yi < y && yj >= y ||
        yj < y && yi >= y)
      if (xi + (y - yi) / (yj - yi) * (xj - xi) < x)
        oddNodes = !oddNodes
      end
    end

    last_point = p
  end

  oddNodes
end