flickrのgeotagついてる写真を収集してたので、kml出力するようにした

railsで。飛行機の中で暇だったので作った。

dbのmigrate

class CreatePhotos < ActiveRecord::Migration
  def self.up
    create_table :photos do |t|
      t.column :photo_id, :string, :limit => 20, :null => false
      t.column :title, :string, :limit => 30, :null => false
      t.column :page_url, :string, :limit => 128, :null => false
      t.column :source_url, :string, :limit => 128, :null => false
      t.column :lat, :double, :null => false
      t.column :lon, :double, :null => false
      t.timestamps
    end
  end

  def self.down
    drop_table :photos
  end
end

config/initializers/mime_types.rb に

Mime::Type.register_alias "application/xml", :kml

を追加

(initializerなので、webricを再起動しないと反映されない)

app/controllers/photos_controller.rb に

  # GET /photos/new
  # GET /photos/new.xml
  def new
    @photo = Photo.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @photo }
      format.kml  { render :kml => @photo }
    end
  end

app/views/photos/index.kml.erb を作成

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.1">
<Document>
	<name>flickr geophoto</name>
    <% for photo in @photos %>
	<Style id="geophoto<%=h photo.photo_id %>">
		<IconStyle>
			<color>ffffffff</color>
			<scale>2</scale>
			<Icon>
				<href><%=h photo.source_url %></href>
			</Icon>
			<hotSpot x="20" y="20" xunits="pixels" yunits="pixels"/>
		</IconStyle>
	</Style>
	<Placemark>
		<name><%=h photo.title %></name>
		<LookAt>
			<longitude><%=h photo.lon %></longitude>
			<latitude><%=h photo.lat %></latitude>
			<altitude>0</altitude>
			<range>110000</range>
			<tilt><%= rand(90) %></tilt>
			<heading><%= rand(360) %></heading>
			<altitudeMode>RelativeToGroundAltitudeGE</altitudeMode>
		</LookAt>
		<styleUrl>#geophoto<%=h photo.photo_id %></styleUrl>
		<Point>
			<coordinates><%=h photo.lon %>,<%=h photo.lat %></coordinates>
		</Point>
    </Placemark>
    <% end %>
</Document>
</kml>

photos.kmlが出てるはず

GoogleEarthの左のバーのタブ「場所」の中で右クリックして、「ネットワークリンクの追加」
http://localhost:3000/photos.kml
を追加すればok