【読了時間:5分】
Google Geocoding APIを用いたジオコーディングについて紹介いたします。ここではRuby言語を用いて、住所から緯度経度を取得するプログラムを作成します。
ここではRubyのライブラリである’uri’と’net/http’を用いて通信を行います。成功すると、XML形式にてGoogleから結果が返ってきます。’rexml/document’ライブラリを用いて、緯度経度が格納されているタグから緯度経度を取得します。
#!ruby
# coding: utf-8
require 'net/http'
require 'uri'
require 'rexml/document'
#入力したい住所
address = "東京都港区六本木7丁目"
#HTTP Client
#URI.parse: uri object
url_object = URI.parse('http://maps.googleapis.com/maps/api/geocode/xml?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true')
puts url_object
Net::HTTP.version_1_2
response = Net::HTTP.get_response(url_object)
case
when Net::HTTPSuccess
response
when Net::HTTPRedirection
fetch(response['location'], limit - 1)
else
response.error!
end
doc = REXML::Document.new(response.body)
location = doc.elements['GeocodeResponse/result/geometry/location']
puts location.elements['lat'].text
puts location.elements['lng'].text
緯度・経度は表示されましたか?とても便利なAPIですね。
【執筆:仙石裕明】