From 0befaaf27e19b32e4a5bd703445a3ecd356fe61e Mon Sep 17 00:00:00 2001 From: Alex Reisner <alex@alexreisner.com> Date: Tue, 3 Nov 2009 17:19:34 -0500 Subject: [PATCH] Fix a typo, clean up code, use full references to Math module methods. --- lib/geocoder.rb | 26 +++++++++++++------------- test/geocoder_test.rb | 5 ++++- 2 files changed, 17 insertions(+), 14 deletions(-) diff --git a/lib/geocoder.rb b/lib/geocoder.rb index a68acff5..917a2ad2 100644 --- a/lib/geocoder.rb +++ b/lib/geocoder.rb @@ -215,28 +215,28 @@ module Geocoder ## # Compute the geographic center (aka geographic midpoint, center of - # gravity) for an array of [lat,lon] points. + # gravity) for an array of [lat,lon] points. Follows the procedure + # documented at http://www.geomidpoint.com/calculation.html. # def self.geographic_center(points) # convert to Cartesian coordinates - x = []; y = [], z = [] + 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]) + 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 coordinates - avg = [x,y,z].map do |c| - c.inject(0){ |tot,i| tot += i } + + # compute average coordinate values + xa, ya, za = [x,y,z].map do |c| + c.inject(0){ |tot,i| tot += i } / c.size.to_f end # convert back to latitude/longitude - xa, ya, za = avg - lon = atan2(ya, xa) - hyp = sqrt(xa * xa + ya * ya) - lat = atan2(za, hyp) + lon = Math.atan2(ya, xa) + hyp = Math.sqrt(xa * xa + ya * ya) + lat = Math.atan2(za, hyp) [lat,lon] end diff --git a/test/geocoder_test.rb b/test/geocoder_test.rb index b7c18f47..ce19947d 100644 --- a/test/geocoder_test.rb +++ b/test/geocoder_test.rb @@ -15,6 +15,9 @@ class GeocoderTest < Test::Unit::TestCase # sanity check def test_geographic_center - assert_equal 69, Geocoder.geographic_center([[0,0], [0,1]]).round + assert_equal [0.0, 0.5], + Geocoder.geographic_center([[0,0], [0,1]]) + assert_equal [0.0, 1.0], + Geocoder.geographic_center([[0,0], [0,1], [0,2]]) end end -- GitLab