Skip to content
Snippets Groups Projects
Commit 9d9208f2 authored by Alex Reisner's avatar Alex Reisner
Browse files

Add geographic_center class method.

parent fc0b5ba9
No related branches found
No related tags found
No related merge requests found
......@@ -214,6 +214,34 @@ module Geocoder
c * units[options[:units]]
end
##
# Compute the geographic center (aka geographic midpoint, center of
# gravity) for an array of [lat,lon] points.
#
def self.geographic_center(points)
# convert to Cartesian coordinates
x = []; y = [], z = []
points.each do |p|
x << cos(p[0]) * cos(p[1])
y << cos(p[0]) * sin(p[1])
z << sin(p[0])
end
# compute average coordinates
avg = [x,y,z].map do |c|
c.inject(0){ |tot,i| tot += i }
end
# convert back to latitude/longitude
xa, ya, za = avg
lon = atan2(ya, xa)
hyp = sqrt(xa * xa + ya * ya)
lat = atan2(za, hyp)
[lat,lon]
end
##
# Convert degrees to radians.
#
......
......@@ -7,4 +7,14 @@ class GeocoderTest < Test::Unit::TestCase
assert_equal [40.7495760, -73.9916733], v.fetch_coordinates
assert_equal [40.7495760, -73.9916733], [v.latitude, v.longitude]
end
# sanity check
def test_distance_between
assert_equal 69, Geocoder.distance_between(0,0, 0,1).round
end
# sanity check
def test_geographic_center
assert_equal 69, Geocoder.geographic_center([[0,0], [0,1]]).round
end
end
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment