Skip to content

Instantly share code, notes, and snippets.

@burubur
Created January 31, 2020 08:41
Show Gist options
  • Save burubur/f86fc3c8215547fab7329773345a6dee to your computer and use it in GitHub Desktop.
Save burubur/f86fc3c8215547fab7329773345a6dee to your computer and use it in GitHub Desktop.
ruby - midpoint calculation
def midpoint(points)
return [] if points.blank?
coords = points.map {|p| new(*p).to_radians if p.present?}.compact
# convert to Cartesian coordinates
x = []
y = []
z = []
coords.each do |p|
x << Math.cos(p[0]) * Math.cos(p[1])
y << Math.cos(p[0]) * Math.sin(p[1])
z << Math.sin(p[0])
end
# compute average coordinate values
xa, ya, za = [x, y, z].map do |c|
c.inject(0) {|acc, i| acc + i} / c.size.to_f
end
# convert back to latitude/longitude
lon = Math.atan2(ya, xa)
hyp = Math.sqrt(xa ** 2 + ya ** 2)
lat = Math.atan2(za, hyp)
new(lat, lon).to_degrees
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment