ひとつのGeoHexをKMLにするSinatraワンファイル・サーバ

一つの GeoHex を KML にして送り出すワンファイル・サーバを作ることができました。

the code

#server.rb
require 'rubygems'
require 'sinatra/base'
require 'haml'
require 'gh.rb' # @see http://d.hatena.ne.jp/hfu/20110224

class App < Sinatra::Base
  get '/' do
    redirect '/geohex/hcawP'
  end

  get '/geohex/:geohex' do |geohex|
    content_type 'application/vnd.google-earth.kml+xml' # easier than apache!
    #content_type 'text/plain' # good for testing purpose
    coords = GeoHex::Zone.new(geohex).hexCoords
    coords << coords[0]
    haml <<-EOS
%kml(xmlns='http://earth.google.com/kml/2.0')
  %Document
    %Style(id='geohexpolygon')
      %LineStyle
        %color ff0000ff
        %width 2
      %PolyStyle
        %fill 0
    %Placemark
      %name GeoHex #{geohex}
      %styleUrl #geohexpolygon
      %Polygon
        %extrude 1
        %outerBoundaryIs
          %LinearRing
            %coordinates #{coords.map{|h| "#{h[:lon]},#{h[:lat]}"}.join(" ")}
    EOS
  end
end

App.run! :port => 8092

サーバスタート方法:

$ ruby server.rb
== Sinatra/0.9.4 has taken the stage on 8092 for development with backup from Thin
>> Thin web server (v1.2.5 codename This Is Not A Web Server)
>> Maximum connections set to 1024
>> Listening on 0.0.0.0:8092, CTRL+C to stop

これを立ち上げておいて、http://localhost:8092/ にアクセスすると、http://localhost:8092/geohex/hcawP にリダイレクトされて、Google Earth に GeoHex hcawP が赤色の線で描画されます。

それにしても別アプリは

それにしても、application/vnd.google-earth.kml+xml に反応して別アプリがたちあがる、という作りは、ユーザを待たせます。ブラウザとのインタラクションも切れてしまいます。やはり、Google Earthプラグイン化の意味は大きいと思います。
GeoHex SuperOverlay の実験後に、プラグイン対応を考えてみたいと思っています。