我需要通过Google地理编码API对经/纬度进行反向查找,并返回其提供的地址。
如果返回的地址不止一个,我希望将其追加为另一行。
我引用了this thread并尽了最大可能对其进行了修改,但是我认为urllib.parse.quote文章中缺少关键的内容。
input.csv
"site_inst","lat","long"
"1","33.873859","-118.290922"
"2","34.06139","-117.674721"
"3","33.911388","-118.208885"
python
import csv
import urllib
import urllib.request
import json
googleGeocodeUrl = 'https://maps.googleapis.com/maps/api/geocode/json?latlng={},{}&key={}&result_type={}'
result_type = 'street_address'
key = '123'
with open('input.csv', newline='') as f_input, open('output.csv', 'w', newline='') as f_output:
csv_input = csv.reader(f_input)
csv_output = csv.writer(f_output)
csv_output.writerow(['formatted_address', 'lat', 'long'])
for site_inst, lat, long in csv_input:
url = googleGeocodeUrl.format(urllib.parse.quote(site_inst), lat, long, key, result_type)
json_response = urllib.request.urlopen(url)
search = json_response.read().decode('utf-8')
searchjson = json.loads(search)
for place in searchjson['results']:
row = [place['formatted_address'], place['geometry']['location']['lng'], place['geometry']['location']['lat']]
# Output to CSV
# csv_output.writerow(row)
# Output to jupyter notebook for review
print(row)
api输出
{
"plus_code": {
"compound_code": "VPF5+GJ Los Angeles, CA, USA",
"global_code": "8553VPF5+GJ"
},
"results": [
{
"address_components": [
{
"long_name": "17257",
"short_name": "17257",
"types": [
"street_number"
]
},
{
"long_name": "Vermont Avenue",
"short_name": "Vermont Ave",
"types": [
"route"
]
},
{
"long_name": "Gardena",
"short_name": "Gardena",
"types": [
"locality",
"political"
]
},
{
"long_name": "Los Angeles County",
"short_name": "Los Angeles County",
"types": [
"administrative_area_level_2",
"political"
]
},
{
"long_name": "California",
"short_name": "CA",
"types": [
"administrative_area_level_1",
"political"
]
},
{
"long_name": "United States",
"short_name": "US",
"types": [
"country",
"political"
]
},
{
"long_name": "90247",
"short_name": "90247",
"types": [
"postal_code"
]
}
],
"formatted_address": "17257 Vermont Ave, Gardena, CA 90247, USA",
"geometry": {
"location": {
"lat": 33.8738528,
"lng": -118.2909792
},
"location_type": "RANGE_INTERPOLATED",
"viewport": {
"northeast": {
"lat": 33.8752017802915,
"lng": -118.2896302197085
},
"southwest": {
"lat": 33.87250381970851,
"lng": -118.2923281802915
}
}
},
"place_id": "EikxNzI1NyBWZXJtb250IEF2ZSwgR2FyZGVuYSwgQ0EgOTAyNDcsIFVTQSIcEhoKFAoSCSdCkf6YysKAEXwSueZbsvC5EOmGAQ",
"types": [
"street_address"
]
}
],
"status": "OK"
}
所需的csv输出
"site_inst","lat","long","formatted_address"
"1","33.873859","-118.290922","17257 Vermont Ave, Gardena, CA 90247, USA"
"2","34.06139","-117.674721","1267 Brooks St, Ontario, CA 91762, USA"
"2","34.06139","-117.674721","1269 Brooks St, Ontario, CA 91762, USA"
"3","33.911388","-118.208885","3646 N Long Beach Blvd, Compton, CA 90221, USA"
"3","33.911388","-118.208885","2289 N Long Beach Blvd, Compton, CA 90221, USA"
如果我也可以将“ address_components”另存为列,那将是惊人的,但我首先需要基本功能和4个字段。
任何提示都很棒。