Skip to content

Instantly share code, notes, and snippets.

@markdturner
Forked from gtarawneh/get_addresses.py
Last active April 7, 2020 07:14
Show Gist options
  • Save markdturner/c6d565292bd2b8504c4516996456d697 to your computer and use it in GitHub Desktop.
Save markdturner/c6d565292bd2b8504c4516996456d697 to your computer and use it in GitHub Desktop.
import json
import csv
import requests
import os
"""
Simple tool to fetch the lat, lng coordinates of a list of addresses.
Requirements:
1. The tool requires "requests", a popular Python package, which can be
installed with "pip install requests".
2. This requires an API_KEY for the Google Maps Platform which can be obtained
by following the instructions here ...
https://developers.google.com/maps/documentation/geocoding/get-api-key
3. The tool requires an API_KEY for getaddresses.io, contact [email protected] for details
4. The tool requires a CSV file loaded with all the postcodes for the area of interest to be present in the same directory and named 'postcodes.csv'
"""
ADDRESS_API_KEY = "adresses.io-api-key"
GMAPS_API_KEY = "google-maps-geocoding-api-key"
addressURL = "https://api.getAddress.io/find/"
geocodeURL = "https://maps.googleapis.com/maps/api/geocode/json"
addresses = []
def get_addresses(postcode):
"""Return the addresses for a given postcode.
Inputs:
postcode (str): e.g. "NE1 7RU"
Returns:
address (list): e.g. ["Newcastle University, Newcastle upon Tyne, UK"]
"""
print("Fetching addresses for " + postcode)
r = requests.get(addressURL + postcode + "?api-key=" + ADDRESS_API_KEY)
data = r.json()
return data["addresses"]
def get_location(address):
"""Return the location of an address.
Inputs:
address (str): e.g. "Newcastle University, Newcastle upon Tyne, UK"
Returns:
location (tuple): (lat, lng)
"""
params = {"key": GMAPS_API_KEY, "address": address}
repsonse = requests.get(geocodeURL, params)
results = repsonse.json()["results"]
location = results[0]["geometry"]["location"]
return (location["lat"], location["lng"])
def main():
# open the postcodes file
file = open(os.path.join("postcodes.csv"), "rU")
reader = csv.reader(file, delimiter=",")
# write addresses to file for backup
with open('addresses.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["Address,Postcode"])
for row in reader:
postcode = row[0]
postcode_addresses = (get_addresses(postcode))
# add addresses to global list
addresses.extend(postcode_addresses)
for address in postcode_addresses:
writer.writerow([address,postcode])
with open('locations.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["Location"])
# fetch a geolocation for every address
for address in addresses:
location = get_location(address)
print(location)
writer.writerow([location])
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment