-
Notifications
You must be signed in to change notification settings - Fork 1
/
geocode_geopy.py
84 lines (68 loc) · 2.37 KB
/
geocode_geopy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
"""
Name: geocode_geopy.py
Author: William A Loring
Created: 07/10/2021
Purpose: Geocode using Nominatim from geopy
"""
# Windows: pip install geopy
# Linux: pip3 install geopy
from geopy.geocoders import Nominatim
def main():
# Test forward geocode
city = input("Enter City: ")
state = input("Enter State: ")
country = input("Enter Country: ")
print(geocode(city, state, country))
# Test reverse geocode
LAT = 41.8666
LON = -103.6672
print(reverse_geocode(LAT, LON))
# -------------------------- GEOCODE --------------------------------------#
def geocode(city, state, country):
"""Get lat, lng, and address using geopy
from city, state, and country
"""
try:
# Create geolocator object with Nominatim geocode service
# Nominatim is a free geolocater that uses openstreetmaps.org
geolocator = Nominatim(user_agent="location_practice")
# Create location dictionary for geocode request
location = {
"city": city,
"state": state,
"country": country
}
# Get geocode object with location data
# lat, lng, address
geo_location = geolocator.geocode(location)
# Uncomment for testing as a program
# print(geo_location.raw)
# print(geo_location.address)
# print((geo_location.latitude, geo_location.longitude))
# Return geocode location information to calling program
return (
geo_location.latitude,
geo_location.longitude,
geo_location.address
)
except Exception as e:
print(f"An error occured while geocoding. {e}")
# ----------------------- REVERSE GEOCODE ---------------------------------#
def reverse_geocode(lat, lon):
"""Reverse geocode from lat, lon using geopy"""
try:
# Create geolocator object
geolocator = Nominatim(user_agent="location_practice")
# Create location tuple
location = (lat, lon)
# Get address with resolution of town
address = geolocator.reverse(location, zoom=10)
# Uncomment For testing as a program
# print(address)
return address
except Exception as e:
print(f"An error occured while geocoding. {e}")
# If a standalone program, call the main function
# Else, use as a module
if __name__ == '__main__':
main()