using the GeoPy - Nominatim reverse geocoding service
I am having difficulties with reverse geocoding.
1) Read the comma-separated file (coords.csv, first table) containing coordinates (latitudes and longitudes),
2) Reverse geocode each coordinate, using the GeoPy - Nominatim reverse geocoding service, and
3) Save the result to a file named "regeo.csv" in an output directory.
5) The resulting CSV file, "regeo.csv" should have only six columns displaying Name, Address, City, State, ZIP, and Country (see example below).
coords.csv
Latitude | Longitude |
37.365825 | -121.932533 |
37.760816 | -122.45099 |
34.040961 | -118.279955 |
32.732594 | -117.182865 |
38.577309 | -121.437613 |
37.714513 | -119.53361 |
36.416937 | -116.969059 |
33.304015 | -115.811139 |
41.199164 | -124.008404 |
39.120116 | -120.061495 |
format for regeo.csv
Name | Address | City | State | ZIP | County |
from geopy.geocoders import Nominatim
filename = "./data/coords.csv"
out_file = "./output/regeo.csv"
data = []
with open(filename, 'r') as file:
for line in file:
line = line.split(",")
line[-1] = line[-1].strip()
data.append(line)
geolocator = Nominatim(user_agent="HTTP")
data[0].append("Latitude")
data[0].append("Longitude")
for i in range(1, len(data)):
address = data[i][2] + ',' + data[i][3] + ',' + data[i][4] + ',' + data[i][5]
location = geolocator.geocode(address)
# check if geolocator could find the location
if location is not None:
data[i].append(str(location.latitude))
data[i].append(str(location.longitude))
# add empty data
else:
data[i].append("")
data[i].append("")
with open(out_file, "w") as file:
for line in data:
line = ",".join(line)
file.write(line + "\n")
Step by step
Solved in 4 steps with 2 images