GeoRuby で読み出した Shapefile の内容を PostGIS に書き出す方法
GeoRuby で読み出した Shapefile の内容を PostGIS に書き出す方法を入門者向きに解説します。
前提
- PostGIS が設定された PostgreSQL データベースにアクセスできる。
- GeoRuby と sequel が Ruby にインストールされている。
Sequel / postgres について
Sequel についての概説としては、d:id:hfu:20090629 が参考になるかもしれません。sequel を Ruby にインストールするには、
$ gem install sequel
としてください。Sequel の裏で PostGIS にアクセスするため、Ruby から PostGIS を扱うライブラリが必要ですが、Windows の場合、次のコマンドでインストールできたと思います。
$ gem install ruby-postgres
Mac OS X の場合には、次のコマンドでインストールできたと思います。
$ sudo gem install postgres -- --with-opt-include=/opt/local/include/postgresql83 --with-opt-lib=/opt/local/lib/postgresql83
postgres の Ruby 1.9 対応
Ruby 1.9 から postgres を使えるようにするのは簡単ではありません。
Ruby1.9からDBIでPostgreSQLに接続 - プログラマー'sペイジ
Sinatra, Sequel, HAML, PostgreSQL, UTF-8 and Ruby 1.9.1 | Jonathan.inspect
あたりに記事がありますが、私は、今回については 1.9 での動作をあきらめました。
作成したコード
ホスト名 localhost, ユーザ名 fitter, パスワード happier, データベース名 more_productiveの PostGIS データベースに、データを入れていくコードは次のようになります。
# -*- coding: cp932 -*- #postgis_write.rb $KCODE = 's' require 'rubygems' require 'sequel' require 'geo_ruby' require 'geo_ruby_fix19' DB = Sequel::connect('postgres://fitter:happier@localhost/more_productive', {:encoding => 'SJIS'}) include GeoRuby::Shp4r include GeoRuby::SimpleFeatures DB.drop_table(:hatena_rdedg) if DB.table_exists?(:hatena_rdedg) DB.create_table(:hatena_rdedg) do primary_key :gid String :"種別" String :orgMDId integer :"整備完了日" String :uuid String :"名称" String :id integer :orgGILvl integer :"存在期間自" end DB.select(:AddGeometryColumn.sql_function( '', 'hatena_rdedg', 'the_geom', '4326', 'MULTILINESTRING', 2)).first DB.transaction do ShpFile.open('rdedg.shp') {|shp| shp.each {|r| record = {} r.data.each {|k, v| record[k.to_sym] = v } record[:the_geom] = :ST_GeomFromText.sql_function(r.geometry.as_wkt, 4326) DB[:hatena_rdedg].insert(record) } } end DB.disconnect
DB.create_table で、primary_key :gid としているのは、QGIS で読めるようにするためです。
QGIS 等を使って、データがうまく転送できているか確かめることができます。