使用谷歌地图在Python中进行地理编码

时间:2014-09-04 00:27:01

标签: python file csv geocode

我刚刚编写了这些代码的几个问题。代码如下: -

from googlemaps import GoogleMaps
import urllib, json
import csv

def geocode(addr):
url = "http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false" %    (urllib.quote(addr.replace(' ', '+')))
data = urllib.urlopen(url).read()
info = json.loads(data).get("results")[0].get("geometry").get("location")

return info

with open('addtest.csv', 'rb') as f:
reader = csv.reader(f)
for row in reader:
    row_count = sum(1 for row in reader)
    for i in range(0, row_count):
        r = geocode(row[i])
        print ("%s %s" % (r['lat'], r['lng']))
        csv_out = open('addtest_c.csv', 'wb')
        mywriter = csv.writer(csv_out)
        mywriter.writerows("%s %s" % (r['lat'], r['lng']))

我想要做的是获取地址(逐行),对它们进行地理编码,并在另一个csv文件中写入坐标。如果找不到该位置的坐标,则脚本将在输出csv文件中写入“未找到”。

我尝试了上面的脚本,但输出变为: -

1,.,8,4,9,4,4,2, ,1,0,2,.,9,2,8,8,3,4,1

我的测试文件中有12行(名为addtest.csv),如下所示: -

Kg Sg Nibong,Lubuk,Semerah,Parit Sulong,Batu Pahat,Johor
Kg Parit Bentong,Spg Kiri,Sri Medan,Parit Sulong,Batu Pahat,Johor
Ldg B-1, Yong Peng,Tg Semberong,Yong Peng,Ayer Hitam,Batu Pahat,Johor
Kg Sri Belahan,Sg Kluang,Rengit,Batu Pahat,Batu Pahat,Johor
Parit Besar,Bagan,Semerah,Parit Sulong,Batu Pahat,Johor
Spg Tiga Bagan,Bagan,Semerah,Parit Sulong,Batu Pahat,Johor
Parit Besar,Bagan,Semerah,Parit Sulong,Batu Pahat,Johor
Parit Selulon,Linau,Parit Yaani,Sri Gading,Batu Pahat,Johor
Parit Khalil,Sri Gading,Semarang,Ayer Hitam,Batu Pahat,Johor
Kg Parit Dalam,Sri Medan,Sri Medan,Parit Sulong,Batu Pahat,Johor
Kg Parit Jatuh,Tg Semberong,Yong Peng,Ayer Hitam,Batu Pahat,Johor
Parit Orang Kaya,Bagan,Semerah,Parit Sulong,Batu Pahat,Johor

非常感谢任何帮助。如果您需要更多信息,请发表评论。我在Windows上使用Python 2.7.8。

0 个答案:

没有答案