Skip to content

Instantly share code, notes, and snippets.

@kidbrax
Created September 22, 2011 22:43
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save kidbrax/1236253 to your computer and use it in GitHub Desktop.
Save kidbrax/1236253 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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
Copy link

Really helpful script 😄

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