Skip to content

Instantly share code, notes, and snippets.

@cyrille
Created July 23, 2011 07:27
Show Gist options
  • Save cyrille/1101144 to your computer and use it in GitHub Desktop.
Save cyrille/1101144 to your computer and use it in GitHub Desktop.
Point in polygon (Gmap)
# encoding : utf-8
class Numeric
def to_rad
self.to_f / 180.0 * Math::PI
end
def to_deg
self.to_f * 180.0 / Math::PI
end
end
module PolygonUtilities
#This function returns an array like [{:x => 12, :y => 22}, {:x => 12, :y => 22}, {:x => 12, :y => 22}]
def to_polygon(conv = :rad)
point_tab = []
if conv == :rad
coordinates.split.map{|p| p.split(',')}.each do |e|
point_tab << {:x => e[0].to_f.to_rad, :y => e[1].to_f.to_rad}
end
else
coordinates.split.map{|p| p.split(',')}.each do |e|
point_tab << {:x => e[0].to_f, :y => e[1].to_f}
end
end
point_tab
end
#This function returns true or false whether a point in is in the polygon or not
def point_in_polygon?(lat, lng)
i = 0
p1 = p2 = {}
poly = to_polygon
poly_size = poly.size
p1 = poly[0]
xinters = 0.00
counter = 0
p = {:x => lat.to_rad, :y => lng.to_rad}
while i <= poly_size
p2 = poly[i % poly_size]
if p[:y] > min(p1[:y], p2[:y])
if p[:y] <= max(p1[:y], p2[:y])
if p[:x] <= max(p1[:x],p2[:x])
if p1[:y] != p2[:y]
xinters = (p[:y] - p1[:y]) * (p2[:x] - p1[:x]) / (p2[:y] - p1[:y]) + p1[:x]
if p1[:x] == p2[:x] || p[:x] <= xinters
counter += 1
end
end
end
end
end
p1 = p2
i += 1
end
counter % 2 == 0 ? false : true
end
private
def min(x, y)
x < y ? x : y
end
def max(x, y)
x < y ? y : x
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment