Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Check whether a point is within a polygon #ruby
def point_in_polygon?(polygonPoints)
return false if self.latitude.blank? or self.longitude.blank?
polygonPoints.each do |point|
point[0] = point[0].to_f
point[1] = point[1].to_f
end
contains_point = false
i = -1
j = polygonPoints.size - 1
while (i += 1) < polygonPoints.size
a_point_on_polygon = polygonPoints[i]
trailing_point_on_polygon = polygonPoints[j]
if point_is_between_the_ys_of_the_line_segment?(a_point_on_polygon, trailing_point_on_polygon)
if ray_crosses_through_line_segment?(a_point_on_polygon, trailing_point_on_polygon)
contains_point = !contains_point
end
end
j = i
end
contains_point
end
private
def point_is_between_the_ys_of_the_line_segment?(a_point_on_polygon, trailing_point_on_polygon)
(a_point_on_polygon[0] <= self.latitude && self.latitude < trailing_point_on_polygon[0]) ||
(trailing_point_on_polygon[0] <= self.latitude && self.latitude < a_point_on_polygon[0])
end
def ray_crosses_through_line_segment?(a_point_on_polygon, trailing_point_on_polygon)
(self.longitude < (trailing_point_on_polygon[1] - a_point_on_polygon[1]) * (self.latitude - a_point_on_polygon[0]) /
(trailing_point_on_polygon[0] - a_point_on_polygon[0]) + a_point_on_polygon[1])
end
@kidbrax

This comment has been minimized.

Copy link
Owner Author

@kidbrax kidbrax commented Sep 22, 2011

based on http://jakescruggs.blogspot.com/2009/07/point-inside-polygon-in-ruby.html but uses an object with lat/long and receives the polygon instead of having the polygon as the object receiving the point

@railslauncher

This comment has been minimized.

Copy link

@railslauncher railslauncher commented Jun 15, 2015

Really helpful script 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment