require 'json'
require 'net/http'
require 'resolv-replace'
require 'uri'
class LocalSearch
def initialize(appid)
@appid = appid
end
private
def get(url, headers)
uri = URI.parse(url)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
http.open_timeout = 3
http.read_timeout = 3
res = http.start do |http|
http.get(uri.request_uri, headers)
end
# 左辺にクラス、右辺にインスタンス
if Net::HTTPSuccess === res
res.body
else
res.value # 例外を発生させる
end
end
def json2pois(json)
result = []
data = JSON.parse(json)
data['Feature'].each do |f|
if f['Geometry']['Type'] == 'point'
ll = f['Geometry']['Coordinates'].split(',')
result << {'name' => f['Name'], 'lat' => ll[1], 'lon' => ll[0]}
end
end
result
end
public
def search(query)
base_url = 'https://map.yahooapis.jp/search/local/V1/localSearch'
params = {
'query' => query,
'output' => 'json',
'results' => '3',
'sort' => 'score'
}
url = base_url + '?' + URI.encode_www_form(params)
headers = {'User-Agent' => "Yahoo AppID: #{@appid}"}
json = get(url, headers)
json2pois(json)
end
end
begin
appid = 'YOUR APPLICATION ID' # アプリケーションIDを指定
query = '東京タワー'
pois = LocalSearch.new(appid).search(query)
pois.each do |p|
puts "#{p['name']}\n #{p['lat']}, #{p['lon']}\n\n"
end
rescue Exception => e
puts "ERROR: #{e.message}"
end