2014年12月16日 星期二

Ruby - 中文地址取得經緯度座標

先使用 gem 安裝 Geocoder
> sudo gem install geocoder

執行 irb :
$ irb

> require 'geocoder'
> my = Geocoder.search("10659 臺北市建國南路二段125號")

執行結果:
 => [#[{"long_name"=>"125", "short_name"=>"125", "types"=>["street_number"]}, {"long_name"=>"Section 2, Jianguo South Road", "short_name"=>"Section 2, Jianguo S Rd", "types"=>["route"]}, {"long_name"=>"新龍里", "short_name"=>"新龍里", "types"=>["administrative_area_level_4", "political"]}, {"long_name"=>"Da’an District", "short_name"=>"Da’an District", "types"=>["administrative_area_level_3", "political"]}, {"long_name"=>"Taipei City", "short_name"=>"Taipei City", "types"=>["administrative_area_level_1", "political"]}, {"long_name"=>"Taiwan", "short_name"=>"TW", "types"=>["country", "political"]}, {"long_name"=>"106", "short_name"=>"106", "types"=>["postal_code"]}], "formatted_address"=>"No. 125, Section 2, Jianguo South Road, Da’an District, Taipei City, Taiwan 106", "geometry"=>{"location"=>{"lat"=>25.029152, "lng"=>121.538369}, "location_type"=>"ROOFTOP", "viewport"=>{"northeast"=>{"lat"=>25.0305009802915, "lng"=>121.5397179802915}, "southwest"=>{"lat"=>25.0278030197085, "lng"=>121.5370200197085}}}, "partial_match"=>true, "types"=>["street_address"]}, @cache_hit=nil>] 

取得陣列裡的資料:
 > my[0].latitude
 => 25.029152 
 > my[0].longitude
 => 121.538369 
 > my[0].address
 => "No. 125, Section 2, Jianguo South Road, Da’an District, Taipei City, Taiwan 106" 
 > my[0].city
 => "Da’an District" 

沒有留言: