Bye Bye Moore

PoCソルジャーな零細事業主が作業メモを残すブログ

地理情報や郵便番号の検索ができるGem「Geocoderで遊ぶ」

Geocoderは既存APIをつかって地理情報を検索できる便利Gemです

導入

$ gem install geocoder

基本的な使い方

Geocoder.configure(language: "ja", units: "km", :lookup => :google)
=> {:timeout=>3,
 :lookup=>:google,
 :ip_lookup=>:freegeoip,
 :language=>"ja",
 :http_headers=>{},
 :use_https=>false,
 :http_proxy=>nil,
 :https_proxy=>nil,
 :api_key=>nil,
 :cache=>nil,
 :cache_prefix=>"geocoder:",
 :always_raise=>[],
 :units=>"km",
 :distances=>:linear,
 :chache_prefix=>nil}

Geocoder.search("Tokyo")
=> [#<Geocoder::Result::Google:0x007fed93624f48
  @cache_hit=nil,
  @data=
   {"address_components"=>
     [{"long_name"=>"東京都",
       "short_name"=>"東京都",
       "types"=>["administrative_area_level_1", "political"]},
      {"long_name"=>"日本",
       "short_name"=>"JP",
       "types"=>["country", "political"]}],
    "formatted_address"=>"日本, 東京都",
    "geometry"=>
     {"bounds"=>
       {"northeast"=>{"lat"=>35.8986441, "lng"=>153.9852295},
        "southwest"=>{"lat"=>24.2242343, "lng"=>138.9427579}},
      "location"=>{"lat"=>35.6894875, "lng"=>139.6917064},
      "location_type"=>"APPROXIMATE",
      "viewport"=>
       {"northeast"=>{"lat"=>35.817813, "lng"=>139.910202},
        "southwest"=>{"lat"=>35.528873, "lng"=>139.510574}}},
    "types"=>["administrative_area_level_1", "political"]}>]

郵便番号

ちゃんとクエリを書いてあげれば郵便番号から番号を引く事だってできます。

Geocoder.search("182-8585", params: {contorycodes: "ja"})
=> [#<Geocoder::Result::Google:0x007fed936d7d28
  @cache_hit=nil,
  @data=
   {"address_components"=>
     [{"long_name"=>"182-8585",
       "short_name"=>"182-8585",
       "types"=>["postal_code"]},
      {"long_name"=>"日本",
       "short_name"=>"JP",
       "types"=>["country", "political"]}],
    "formatted_address"=>"〒182-8585, 日本",
    "geometry"=>
     {"location"=>{"lat"=>35.6560942, "lng"=>139.5440317},
      "location_type"=>"APPROXIMATE",
      "viewport"=>
       {"northeast"=>{"lat"=>35.65744318029149, "lng"=>139.5453806802915},
        "southwest"=>{"lat"=>35.6547452197085, "lng"=>139.5426827197085}}},
    "types"=>["postal_code"]}>]

検索エンジンの変更

デフォではgoogleですが、オープンデータ系のものに切り替える事も可能です
例では、nominatimを使っています。

Geocoder.configure(language: "ja", units: "km", :lookup => :nominatim)
=> {:timeout=>3,
 :lookup=>:nominatim,
 :ip_lookup=>:freegeoip,
 :language=>"ja",
 :http_headers=>{},
 :use_https=>false,
 :http_proxy=>nil,
 :https_proxy=>nil,
 :api_key=>nil,
 :cache=>nil,
 :cache_prefix=>"geocoder:",
 :always_raise=>[],
 :units=>"km",
 :distances=>:linear,
 :chache_prefix=>nil}

Geocoder.search("university of electro-communications")
=> [#<Geocoder::Result::Nominatim:0x007fed9364d880
  @cache_hit=nil,
  @data=
   {"place_id"=>"43601982",
    "licence"=>
     "Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright",
...

yahooのようなkeyが必要な物は、別途取得・導入してから使って下さい。