Python:YahooジオコーダAPIを使ってみる
Last-modified: 2013-08-24 (土) 02:14:21 (3753d)
Top / Python:YahooジオコーダAPIを使ってみる
Python:YahooジオコーダAPIを使ってみる †
こんな感じで作ってみました
■Yahoo_Geocoder_API.py
# encoding: utf-8 import urllib,urllib2 from StringIO import StringIO from xml.etree import ElementTree import sys class YOLP_Client(object): ''' YahooジオコーダAPIを使用し、住所から座標情報を取得し、出力するクラスです。 ''' BASE_URL='http://geo.search.olp.yahooapis.jp/OpenLocalPlatform/V1/geoCoder?' def __init__(self,id): self.app_id = id def set_urllib2_param(self, param): if param['proxy']: proxy_handler = urllib2.ProxyHandler(param['proxy']) opener = urllib2.build_opener(proxy_handler) urllib2.install_opener(opener) def execute(self,address): param = urllib.urlencode({'appid':self.app_id,'query':address}) url = self.BASE_URL + param f = urllib2.urlopen(url) if f.code != 200: return None res = "" for l in f.readlines(): res = res + l return res def get_getinfo(self,address): res = self.execute(address) tree = ElementTree.parse(StringIO(res)) element = tree.find('{http://olp.yahooapis.jp/ydf/1.0}Feature') id = element.find('{http://olp.yahooapis.jp/ydf/1.0}Id').text name = element.find('{http://olp.yahooapis.jp/ydf/1.0}Name').text geometory = element.find('{http://olp.yahooapis.jp/ydf/1.0}Geometry/{http://olp.yahooapis.jp/ydf/1.0}Coordinates').text return {'id':id,'name':name,'geometory':geometory} if __name__ == '__main__': if len(sys.argv) < 3 or len(sys.argv) > 4: print 'usage: python Yahoo_Geocoder_API.py [app_id] [住所] [proxy]' print 'output is [lon,lat] [input住所] [output住所] [地方公共団体コード]' exit(1) client = YOLP_Client(sys.argv[1]) # proxy指定がある場合 if len(sys.argv) == 4: client.set_urllib2_param({'proxy':{"http":sys.argv[3]}}) res = client.get_getinfo(sys.argv[2]) print res['geometory'].split(",")[1]+","+res['geometory'].split(",")[0] ,sys.argv[2], res['name'],res['id']
使い方はこんな感じ。
python Yahoo_Geocoder_API.py [APIキー] 東京都
出力はこんな感じ
35.65806720,139.75159890 東京都 東京都港区 13103
出力を地図にマーキングして確認 †
サンプルのhtml(JavaScript?)を作ってみました。
添付ファイルをダウンロードしてみてくださいw
ElementTree?のtips †
解析対象のXMLでネームスペースが使用されている場合、こんな感じでfindしないといけないらしい。
element = tree.find('{http://olp.yahooapis.jp/ydf/1.0}Feature')
ちなみに、デバッガで変数の中身(elementのtagのなか)を見ると、こいつらがタグ名をどうやって内部で保持しているかわかります。
一部だけみてみるとこんな感じw
str: {http://olp.yahooapis.jp/ydf/1.0}Feature
へー