ruby-on-railsgeokit

Get bounding box from array of points


I have a Rails 5 API only project. I have nodes that have latitude/longitude details stored on them. I am using the Rails Geokit gem to do some of the other geographic work.

I want to return to the consuming client the bounding box that contains all of the points contained in an array. Is there a simple way to do this? Most of the examples show you using an already known bounding box, not generating one.


Solution

  • All you need in order to determine the bounding box for a set of coordinates is the min and max of both latitude and longitude, i.e. the extreme west, east, north, and south values. From these you can construct the southwest and northeast points that span the bounding box.

    Now I'm not familiar with geokit, so I don't know the class name of a coordinate, but you should be able to translate that to the correct class name (I'm calling it Point):

    points = [...] # List of nodes
    west, east = points.map(&:longitude).minmax
    south, north = points.map(&:latitude).minmax
    sw = Point.new(longitude: west, latitude: south)
    ne = Point.new(longitude: east, latitude: north)