views:

40

answers:

1

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

+1  A: 

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}
Mike Richards