Skip to content

Instantly share code, notes, and snippets.

@Diego-Thomaz
Last active September 20, 2019 20:34
Show Gist options
  • Select an option

  • Save Diego-Thomaz/bac63d613d7782834d11a428617f4a9d to your computer and use it in GitHub Desktop.

Select an option

Save Diego-Thomaz/bac63d613d7782834d11a428617f4a9d to your computer and use it in GitHub Desktop.
Code to convert geometric circle to polygon using ruby
class ConvertCircleToPolygon
EARTH_RADIUS = 6378137
def to_radians(angle_in_degrees)
angle_in_degrees * Math::PI / 180
end
def to_degrees(angle_in_radians)
angle_in_radians * 180 / Math::PI
end
def calc_offset(c1, distance, bearing)
lat1 = to_radians(c1[1])
lon1 = to_radians(c1[0])
dByR = distance.to_f / EARTH_RADIUS
lat = Math.asin(
Math.sin(lat1) * Math.cos(dByR) +
Math.cos(lat1) * Math.sin(dByR) * Math.cos(bearing))
lon = lon1 + Math.atan2(
Math.sin(bearing) * Math.sin(dByR) * Math.cos(lat1),
Math.cos(dByR) - Math.sin(lat1) * Math.sin(lat))
[to_degrees(lon), to_degrees(lat)]
end
def circle_to_polygon(center, radius, vertices = 32)
flatCoordinates = []
for i in 0..vertices
flatCoordinates.push.concat([calc_offset(center, radius, 2 * Math::PI * i / vertices)])
end
flatCoordinates.push.concat([flatCoordinates.first])
[flatCoordinates.reverse()]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment