Using a geokit or other ruby ​​stone to calculate the center of a series of geo-coordinates

I have been using geokit and geokit-rails gem for rails for a while, but one question that I have not found an answer to is how to find a calculated aggregate center for a set of points. I know how to calculate the distance between two points, but no more than 2.

My reason is that I have a number of points in one city ... everything that is ideal, the city will have a center that I could use, but in some cities, say, Berlin does not have an ideal center. They have several centers, and I just want to use the entire list of places that I have in my database to calculate the center for a specific distribution. Has anyone else had this problem?

Any tips? Thanks

+6
ruby ruby-on-rails google-maps rubygems geokit
source share
1 answer

Having never used Geokit before, the math behind this operation is relatively easy to implement. Assuming these points are made up of latitude and longitude, you just need the average latitude and average longitude for all points. Once you have these two meanings, you have a center.

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

Similarly, if these points are Geokit::LatLng objects instead of a 2-dimensional array, you can simply list their lat and lng values ​​by simply typing #to_a beforehand.

 points.map(&:to_a).transpose.map{|c| c.inject{|a, b| a + b}.to_f / c.size} 
+4
source share

All Articles