Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using geokit or other ruby gem to calculate the center of a series of geo coordinates

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

like image 900
holden Avatar asked Oct 20 '10 11:10

holden


1 Answers

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}
like image 73
Michael Richards Avatar answered Sep 29 '22 16:09

Michael Richards