Wednesday, July 18, 2012

RGeo + Read shapefiles (.shp) + Ubuntu 12.04

Our objective is to read shapefiles using the RGeo gem in a Ruby program.

1. Install GEOS.
2. RGeo is a geospatial data library for Ruby.
   gem install rgeo 

3. RGeo::Shapefile is an optional module for RGeo for reading geospatial data from ESRI shapefiles.

   gem install rgeo-shapefile

 

Download a sample shapefile to test the code, (3 files - test.shp, test.dbf, test.shx).

Paste the following lines of code in a ruby file and run it.

require 'rgeo/shapefile'

RGeo::Shapefile::Reader.open('test.shp') do |file|
  puts "File contains #{file.num_records} records."
  file.each do |record|
    puts "Record number #{record.index}:"
    puts "  Geometry: #{record.geometry.as_text}"
    puts "  Attributes: #{record.attributes.inspect}"
  end
  file.rewind
  record = file.next
  puts "First record geometry was: #{record.geometry.as_text}"
end

 

If GEOS library is not installed then it may produce the following error:-

/var/lib/gems/1.9.1/gems/rgeo-shapefile 0.2.3/lib/rgeo/shapefile/reader.rb:623:in
`_read_polygon': GEOS is not available, but is required for correct interpretation
of polygons in shapefiles. (RGeo::Error::RGeoError)