Skip to content

Instantly share code, notes, and snippets.

@GrHalbgott
Last active March 20, 2025 10:57
Show Gist options
  • Save GrHalbgott/e5ca2453d4eb1fbb2fd303526759ca7a to your computer and use it in GitHub Desktop.
Save GrHalbgott/e5ca2453d4eb1fbb2fd303526759ca7a to your computer and use it in GitHub Desktop.
Showcasing the workflow of geocoding an area-of-interest polygon using Nominatim
import sys
import geopandas as gpd
from geopy.geocoders import Nominatim
from shapely import wkt
# To run this script, you need to have geopy and geopandas installed:
# python -m venv .venv
# source .venv/bin/activate
# python -m pip install geopy geopandas
def retrieve_area(aoi_name: str, user_agent: str) -> gpd.GeoDataFrame:
"""Geocode area of interest."""
try:
geolocator = Nominatim(user_agent=user_agent)
location = geolocator.geocode(aoi_name, geometry='wkt', exactly_one=False)
# Initialize lists to store data
osm_ids = []
names = []
geometries = []
for loc in location:
osm_ids.append(loc.raw['osm_id'])
names.append(str(loc))
geometries.append(wkt.loads(loc.raw['geotext']))
# Create GeoDataFrame from lists
aoi_gdf = gpd.GeoDataFrame(
{
'osm_id': osm_ids,
'name': names,
'geometry': geometries
},
crs='EPSG:4326'
)
except Exception as e:
print(f'Could not retrieve area: {e}')
sys.exit(0)
return aoi_gdf
if __name__ == '__main__':
aoi_name = 'Rio de Janeiro'
user_agent = 'random_user'
aoi_gdf = retrieve_area(aoi_name, user_agent)
aoi_gdf.to_file('output.gpkg', driver='GPKG')
print('Area of interest saved to output.gpkg')
@GrHalbgott
Copy link
Author

More info on GeoPy and Nominatim here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment