8

I've been using the geokit and geokit-rails gem for rails for awhile but one question I haven't found answered is how to find the calculated aggregate center for a collection of points. I know how to calculate the distance between two points, but not more than 2.

My reason is, I have a series of points all in the same city... all things being perfect the city would have a center which I could just use, but some cities, say berlin do not have a perfect center. They have multiple centers, and I just want to use the whole list of places I have in my database to calculate a center for a particular distribution. Has anyone else had this problem?

Any tips? Thanks

holden
  • 13,471
  • 22
  • 98
  • 160

1 Answers1

6

Having never used Geokit before, the math behind this operation is relatively simple to implement yourself. Assuming these points consist of a latitude and a longitude, you just need the average latitude and average longitude for all the points. Once you have those two values, you've got your center point.

points = [[14, 19], [-5, 57], [23, -12]]
points.transpose.map{|c| c.inject{|a, b| a + b}.to_f / c.size}

Likewise, if these points are Geokit::LatLng objects instead of a 2-dimensional array, you can just map their lat and lng values simply by calling #to_a on them beforehand.

points.map(&:to_a).transpose.map{|c| c.inject{|a, b| a + b}.to_f / c.size}
Michael Richards
  • 1,791
  • 14
  • 19
  • 3
    It's worth nothing, things are bit more complicated than just averaging if you're looking for precision: http://www.geomidpoint.com/calculation.html – Sam Soffes Feb 19 '16 at 05:48