iRSSの日記

はてなダイアリーiRSSの日記の続き

GeoKitで地図をジオ系を簡単に

GeoKitなるものを見つけました
ジオコーディング、距離計算等を支援してくれる、プラグインのようです。

Geokit is a Rails plugin for building location-based apps. It provides geocoding, location finders, and distance calculation in one cohesive package. If you have any tables with latitude/longitude columns in your database, or if you every wanted to easily query for "all the stores within a 50 mile radius," then GeoKit is for you.

機能概要

  • Distance calculations, for both flat and spherical environments. For example,

given the location of two points on the earth, you can calculate the miles/KM
between them.(距離の計算をするよ。KMもマイルも使えるよ。)
 

  • ActiveRecord distance-based finders. For example, you can find all the points

in your database within a 50-mile radius.(距離で検索できるよ。たとえば、半径50KMとかで絞れる)

  • Geocoding from multiple providers. It currently supports Google, Yahoo,

Geocoder.us, and Geocoder.ca geocoders, and it provides a uniform response
structure from all of them. It also provides a fail-over mechanism, in case
your input fails to geocode in one service.(いろんなジオコーダーに対応、Googleを使えば、漢字の地名もOK)

  • IP-based location lookup utilizing hostip.info. Provide an IP address, and get

city name and latitude/longitude in return(IPで都市名と緯度経度を取得するよ。http://www.hostip.info/の情報を利用しているよ)

  • A before_filter helper to geocoder the user's location based on IP address,

and retain the location in a cookie.


ActiveRecordで距離検索ができということは、要するに、MySQLでややこしい、距離検索SQLを書かなくてもすむということだと、うれしいです。
↓こういうやつですね

# SELECT id,name,((sqrt((($x - x) * ($x - x)) + (($y - y) * ($y - y))) / 1000) * 0.621) 
AS distance 
FROM companies HAVING distance <= $miles ORDER BY distance ASC LIMIT xx

インストール

Railsのプロジェクトを作っておいて、以下のコマンドをたたく。

ruby script/plugin install svn://rubyforge.org/var/svn/geokit/trunk

初期設定

[Rails Project]/config/enviroment.rbの65行目あたりに GoogleMapsのAPI Keyを入力
GeoKitはenviroment.rbに、API Key設定行を使いしてくれているので、そこを書き換える

# This is your Google Maps geocoder key.
# See http://www.google.com/apis/maps/signup.html
# and http://www.google.com/apis/maps/documentation/#Geocoding_Examples
GeoKit::Geocoders::GOOGLE='ここを、APIKEYで置き換える'

あと、GeoKit::Geocoders::MultiGeocoderを使うと、複数のジオコーダーを順番にめぐってくれたりする模様。その優先順位を、以下の定数で設定。選択肢は

  1. :google
  2. :yahoo
  3. :us
  4. :ca

の4つ
だけど、日本語が通るのはgoogleだけかな?

GeoKit::Geocoders::PROVIDER_ORDER=[:google,:us]