Create a ShapeFile with Ruby

August 20, 2007

Here’s a quick snippet on how to install and create a ShapeFile from data in your Model.

The setup

  1. Download and Install ShapeLib. Make sure to note where the install puts the libshp.so and the shapefil.h (you may need that information later).
  2. Download ruby-shapelib
  3. Unzip ruby-shapelib and run: “ruby ./extconfig.rb”. Depending where step 1 put your files,you made to alter some options you pass to this program. Specifically—with-shapelib-dir and—with-shapelib-include
  4. Once you’ve done that, make sure everything is working right with irb:
$ irb
>> require 'shapelib'
=> true

If you get “true”, you’re good to go.

Simple example

Let’s say we have a table called markers, with the fields lat (float), lng (float), and created_at (datetime). We want to create a shapefile for the points and also collect the time (created_at) as an attribute in the shapefile.

require 'shapelib'

# Create a shapefile from an array of markers
def make_shapefile(markers)
  # Create the shapefile.
  # First argument: is the name of the file to create
  # Second: The shapefile type
  # Third: An array of array(s) describing the attribute (name, type, size)
  fp = ShapeLib::ShapeFile::new("test1.shp",:Point, [['date', :String, 32]])

  # Loop over the markers
  markers.each do |m|
    point = ShapeLib::Point::new(m.lng,m.lat,{"date" => m.created_at})
    fp.write point
  end

  fp.close
end

# try it out...
make_shapefile( Marker.find(:all) )

If all is working right, you should end up with 3 files: test1.shp, test1.shx, and test1.dbf

If you don’t have one already, here’s a nice open-source application to tinker with your new shapefiles: qgis

Trackbacks

Unfortunately, due to spammers I've had to close both trackbacks and comments.

Comments

Comments are closed.