I tried to get the information of the nearest station from the address with ruby.
Get here https://e.developer.yahoo.co.jp/dashboard/
-Encode the requested address to url ・ Request with open-uri The response looks like this
Get it using REXML. It is stored in the coordinates tag.
Click here for url
http://express.heartrails.com/api/xml?method=getStations&x=#{lon}&y=#{lat}"
The response returned is like this (multiple returns in order of closeness: eyes :)
As mentioned above, the station information is included in the station tag. Specify the first station tag because it contains multiple station information.
The code looks like this.
require 'open-uri'
require 'uri'
require "rexml/document"
## 1. request Yahoo API
### 1.1
YAHOO_APP_ID = '[Yahoo app_id]'
### 1.2
ADDRESS ='1-1 Chiyoda, Chiyoda-ku, Tokyo'
p ADDRESS
query = URI.encode_www_form(query: ADDRESS) ##encoding
request_url = "https://map.yahooapis.jp/geocode/V1/geoCoder?appid=#{YAHOO_APP_ID}&#{query}"
### 1.3
res = OpenURI.open_uri(request_url)
doc = REXML::Document.new(res.read)
coordinates = doc.elements['YDF/Feature/Geometry/Coordinates'].text
lon,lat = coordinates.split(',')
p "longitude= #{lon} ,latitude= #{lat}"
## 2. Heart Rails API
### 2.1 1.Request with the latitude and longitude obtained in
heart_rails_request_url = "http://express.heartrails.com/api/xml?method=getStations&x=#{lon}&y=#{lat}"
### 2.2 Scrap the returned nearest station information
res = OpenURI.open_uri(heart_rails_request_url)
doc = REXML::Document.new(res.read)
station = doc.elements['response/station[1]']
name = station.elements['name'].text
line = station.elements['line'].text
distance = station.elements['distance'].text
p name
p line
p distance
The result of requesting the nearest station at the Imperial Palace (1-1 Chiyoda, Chiyoda-ku, Tokyo).
"longitude= 139.75381447 ,latitude= 35.68382285"
"Sakuradamon"
"Tokyo Metro Yurakucho Line"
"740m"
Recommended Posts