Skip to content

Instantly share code, notes, and snippets.

@sillyfellow
Created October 7, 2015 05:41
Show Gist options
  • Save sillyfellow/226751acde84ec488227 to your computer and use it in GitHub Desktop.
Save sillyfellow/226751acde84ec488227 to your computer and use it in GitHub Desktop.
#!/usr/bin/python3
import csv
import json
import urllib.request
import urllib.parse
from time import sleep
def parse_json_response(response):
content = response.readall().decode('utf-8')
result = json.loads(content)
status = result['status']
if status != 'OK':
print("error, my friend")
return
results = result['results']
geometry = results[0]['geometry']
location = geometry['location']
return ', '.join([str(location['lng']), str(location['lat'])])
def fetch_long_lat(address):
url = "https://maps.googleapis.com/maps/api/geocode/json"
values = { 'address' : address }
url_values = urllib.parse.urlencode(values)
full_url = url + '?' + url_values
with urllib.request.urlopen(full_url) as response:
return parse_json_response(response)
def create_address_from_components(row):
"""
A row, coming from a CSV reader, must have these columns.
'Straße', 'HausNr.', 'PLZ', and 'Ort'
"""
street, house, pin, place = row['Straße'].strip(), row['HausNr.'].strip(), row['PLZ'].strip(), row['Ort'].strip()
return ', '.join([' '.join([street, house]), pin, place])
name = "filename.csv"
with open(name) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
address = create_address_from_components(row)
# We need a column 'Nr.'
print(row['Nr'].strip() + ', ', end='', flush=True)
print(fetch_long_lat(address))
sleep(0.5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment